elastic4s geodistance排序查询语法

时间:2015-07-16 16:57:46

标签: scala sorting elasticsearch geolocation elastic4s

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

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
            }
        }
    }
}

}   }'

1 个答案:

答案 0 :(得分:1)

不是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。只是想在这个例子中明确。