简体   繁体   English

Elasticsearch QueryBuilder匹配多个术语

[英]Elasticsearch QueryBuilder Match Multiple Terms

Given JSON in ES index in the following format: 以下列格式给出ES索引中的JSON:

{
    "pin": {
        "id": 123,
        "location": {
            "lat": 456,
            "lon":-789
        }
    }
}

The following gets the document matching the id field: 以下获取与id字段匹配的文档:

client.prepareSearch("index_name")
        .setTypes("pin")
        .setQuery(QueryBuilders.termQuery("id", 123))
        .execute()
        .actionGet();

Instead, I 'm trying to match multiple fields, ie. 相反,我正在尝试匹配多个字段,即。 ( location.lat , location.lon ). location.latlocation.lon )。

QueryBuilders.termQuery(); // accepts only a single term

Tried few alternatives but none of it seems to work, eg: 尝试了一些替代品,但似乎没有任何替代方案,例如:

QueryBuilder queryBuilder = QueryBuilders.boolQuery()
        .must(QueryBuilders.termQuery("location.lat", 456))
        .must(QueryBuilders.termQuery("location.lon", -789));

client.prepareSearch("index_name")
        .setTypes("pin")
        .setQuery(queryBuilder)
        .execute()
        .actionGet();

By default, a geo_point field is not indexed as two fields (location.lat and location.lon), it's indexed as a single field that contains both latitude and longitude. 默认情况下,geo_point字段不会被索引为两个字段(location.lat和location.lon),它会被索引为包含纬度和经度的单个字段。

You can turn on indexing of latitude and longitude by turning on the lat_lon mapping option . 您可以通过打开lat_lon 映射选项打开纬度和经度的索引。 However, in your example, the values for latitude and longitude are too large. 但是,在您的示例中,纬度和经度的值太大。 So, they are normalized, converted to double and indexed as -84.0 and -69.0 instead of 456 and -789. 因此,它们被标准化,转换为double并索引为-84.0和-69.0而不是456和-789。 So, if you will enable lat_lon and replace the value in the queries, you should be able to get the results. 因此,如果您将启用lat_lon并替换查询中的值,您应该能够获得结果。

Please note that values for latitude and longitude are converted to double before indexing. 请注意,在编制索引之前,纬度和经度的值将转换为double。 So using term queries might not be very practical in the long term since you will have to always take rounding errors into consideration. 因此,从长远来看,使用术语查询可能不太实用,因为您必须始终考虑舍入误差。 It might be more useful to use range queries or elasticsearch geospatial queries instead. 使用范围查询或elasticsearch 地理空间查询可能更有用。

查看ElasticSearch中的bool查询 ,您应该能够指定mustshouldshould_not来获取和/或查询的适当混合。

您可以使用QueryBuilders.multiMatchQuery而不是QueryBuilders.termQuery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM