【问题标题】:How to query two types with same field name ElasticSearch with Java code如何使用 Java 代码查询具有相同字段名称 ElasticSearch 的两种类型
【发布时间】:2015-12-08 16:22:31
【问题描述】:

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

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

当我使用 Java 代码进行 elasticsearch 时,我在 prepareSearch.setTypes 中输入了"a,b",然后在 setQuery 中我需要写“location”并且不能写“a.location ”。

我该如何解决这个问题?

【问题讨论】:

    标签: java elasticsearch


    【解决方案1】:

    您需要使用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();
    

    【讨论】:

    • 感谢您的回复,但由于某种原因,我在使用“type_a.location”或“type_b.name”时遇到了异常......当我只使用“location”和“ name" 查询正在运行,但当然不好,因为我也得到 type_b.location 结果...
    • 然后我们可以稍微修改一下查询。我已经相应地更新了我的答案。
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多