0

我使用的是 elastic4s 1.6.2 版,需要编写一个查询来搜索给定的地理位置,按距离对结果进行排序并返回距离。我可以在 curl 中使用 get request 来做到这一点,但很难找到正确的语法,并且示例得到了地理位置排序。

case class Store(id: Int, name: String, number: Int, building: Option[String] =     None, street: String, postCode: String,county: String, geoLocation: GeoLocation)

case class GeoLocation(lat: Double, lon: Double) 

val createMappings = client.execute {
create index "stores" mappings (
  "store" as(
    "store" typed StringType,
    "geoLocation" typed GeoPointType
    )
  )
}

def searchByGeoLocation(geoLocation: GeoLocation) = {
client.execute {
  search in "stores" -> "store" postFilter {
    geoDistance("geoLocation") point(geoLocation.lat, geoLocation.lon) distance(2, KILOMETERS)
  }


}
}

有人知道如何按距地理位置的距离添加排序并获取距离以下 curl 命令按预期工作

curl -XGET 'http://localhost:9200/stores/store/_search?pretty=true' -d '
{
"sort" : [
  {
      "_geo_distance" : {
          "geoLocation" : {
                "lat" : 52.0333793839746,
                "lon" : -0.768937531935448
          }, 
          "order" : "asc",
          "unit" : "km"
      }
  }
],
"query": {
"filtered" : {
    "query" : {
        "match_all" : {}
    },
    "filter" : {
        "geo_distance" : {
            "distance" : "20km",
            "geoLocation" : {
                "lat" : 52.0333793839746,
                "lon" : -0.768937531935448
            }
        }
    }
}

} '

4

1 回答 1

2

不是专家,elasti4s但此查询应该等同于您的 curl 命令:

val geoLocation = GeoLocation(52.0333793839746, -0.768937531935448)
search in "stores" -> "store" query {
    filteredQuery filter {
      geoDistance("geoLocation") point(geoLocation.lat, geoLocation.lon) distance(20, KILOMETERS)
    }
  } sort {
    geoSort("geoLocation") point (geoLocation.lat, geoLocation.lon) order SortOrder.ASC
  }

它打印以下查询:

{
  "query" : {
    "filtered" : {
      "query" : {
        "match_all" : { }
      },
      "filter" : {
        "geo_distance" : {
          "geoLocation" : [ -0.768937531935448, 52.0333793839746 ],
          "distance" : "20.0km"
        }
      }
    }
  },
  "sort" : [ {
    "_geo_distance" : {
      "geoLocation" : [ {
        "lat" : 52.0333793839746,
        "lon" : -0.768937531935448
      } ]
    }
  } ]
}

asc是排序的默认值,因此您可以删除order SortOrder.ASC. 只是想在这个例子中明确一点。

于 2015-07-16T19:43:20.030 回答