在查询中使用已索引的形状

对于那些经常会在查询中使用的形状,可以把它们索引起来以便在查询中可以方便地直接引用名字。 以之前的阿姆斯特丹中央为例,我们可以把它存储为一个类型为 neighborhood 的文档。

首先,我们仿照之前设置 landmark 时的方式建立一个映射:

  1. PUT /attractions/_mapping/neighborhood
  2. {
  3. "properties": {
  4. "name": {
  5. "type": "string"
  6. },
  7. "location": {
  8. "type": "geo_shape"
  9. }
  10. }
  11. }

然后我们索引阿姆斯特丹中央对应的形状:

  1. PUT /attractions/neighborhood/central_amsterdam
  2. {
  3. "name" : "Central Amsterdam",
  4. "location" : {
  5. "type" : "polygon",
  6. "coordinates" : [[
  7. [4.88330,52.38617],
  8. [4.87463,52.37254],
  9. [4.87875,52.36369],
  10. [4.88939,52.35850],
  11. [4.89840,52.35755],
  12. [4.91909,52.36217],
  13. [4.92656,52.36594],
  14. [4.93368,52.36615],
  15. [4.93342,52.37275],
  16. [4.92690,52.37632],
  17. [4.88330,52.38617]
  18. ]]
  19. }
  20. }

形状索引好之后,我们就可以在查询中通过 index, typeid 来引用它了:

  1. GET /attractions/landmark/_search
  2. {
  3. "query": {
  4. "geo_shape": {
  5. "location": {
  6. "relation": "within",
  7. "indexed_shape": { <1>
  8. "index": "attractions",
  9. "type": "neighborhood",
  10. "id": "central_amsterdam",
  11. "path": "location"
  12. }
  13. }
  14. }
  15. }
  16. }

<1> 指定 indexed_shape 而不是 shape,Elasticesearch 就知道需要从指定的文档和路径检索出对应的形状了。

阿姆斯特丹中央这个形状没有什么特别的。同样地,我们也可以使用已经索引好的阿姆斯特丹达姆广场。 这个查询查找出与阿姆斯特丹达姆广场有交集的临近点:

  1. GET /attractions/neighborhood/_search
  2. {
  3. "query": {
  4. "geo_shape": {
  5. "location": {
  6. "indexed_shape": {
  7. "index": "attractions",
  8. "type": "landmark",
  9. "id": "dam_square",
  10. "path": "location"
  11. }
  12. }
  13. }
  14. }
  15. }