我的ElasticSearch中有一个索引-recordsrecords有两种映射类型-type_atype_b,并且每种类型都有名为geo_pointlocation字段。

我想创建一个查询,例如“在特定边界框中具有a.location的所有记录或b.name等于xxxx”。

当我使用Java代码进行Elasticsearch时,在prepareSearch.setTypes中,我放置"a,b",然后在setQuery中,我需要写“location”,而不能写“a.location”。

我该如何解决?

最佳答案

您需要使用QueryBuilders构造查询,以表达对a.locationb.name的约束。它是这样的:

// prepare the bounding box constraint on the location field
QueryBuilder bbox = QueryBuilders.geoBoundingBoxQuery("location")
    .topLeft(40.73, -74.1)
    .bottomRight(40.717, -73.99);
TypeQueryBuilder onlyTypeA = QueryBuilders.typeQuery("type_a");
QueryBuilders bboxTypeA = QueryBuilders.boolQuery()
    .must(bbox)
    .must(onlyTypeA);

// prepare the constraint on the name field
MatchQueryBuilder name = QueryBuilders.matchQuery("name", "xxxx")
TypeQueryBuilder onlyTypeB = QueryBuilders.typeQuery("type_b");
QueryBuilders nameTypeB = QueryBuilders.boolQuery()
    .must(name)
    .must(onlyTypeB);

// prepare the overall OR query
BoolQueryBuilder query = QueryBuilders.boolQuery()
    .should(bboxTypeA)
    .should(nameTypeB)

// create the request and execute it
SearchResponse response = client.prepareSearch("records")
    .setTypes("type_a", "type_b")
    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
    .setQuery(query)
    .execute()
    .actionGet();

关于java - 如何使用Java代码查询具有相同字段名称ElasticSearch的两种类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34160907/

10-15 19:29