用于elasticsearch多字段搜索的java api

9wbgstp7  于 2021-06-13  发布在  ElasticSearch
关注(0)|答案(2)|浏览(456)

在一个索引下,我有一个包含字段的文档 name 以及 location . 现在,用 name “彼得”和 location “巴黎”。
我的java代码是:

SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.termQuery("name", "Peter")).postFilter(QueryBuilders.termQuery("location", "Paris"));

SearchResponse response = null;
    try {
        response = client.search(searchRequest, RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }

上面的代码,不能给我准确的结果。有人能帮我找到正确的方法吗?

pbgvytdp

pbgvytdp1#

在json格式中,您的查询应该如下所示:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "Peter"
          }
        },
        {
          "match": {
            "location": "Paris"
          }
        }
      ]
    }
  }
}
j2cgzkjk

j2cgzkjk2#

您可以使用下面的代码,注意目前您使用的术语是查询 text 字段,这将不允许您进行不区分大小写的匹配,因为它未被分析,通常用于精确搜索。

SearchRequest searchRequest = new SearchRequest("index-name");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (name != null) {
            MatchQueryBuilder nameMatchQueryBuilder = new MatchQueryBuilder("name", name); // replace name with `peter`
            boolQueryBuilder.should(nameMatchQueryBuilder); // change it to `must` if you want this result to be present.
        }
        if (location != null) {
            MatchQueryBuilder locationMatchQueryBuilder = new MatchQueryBuilder("location", location);
            boolQueryBuilder.should(locationMatchQueryBuilder);
        }
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder);
        log.info("Search json {}", searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = esclient.search(searchRequest, RequestOptions.DEFAULT);

另外请注意代码中的注解,因为您可以看到它生成布尔查询,所以如果您希望这两个术语都存在,请替换 boolQueryBuilder.should(nameMatchQueryBuilder); 构造 boolQueryBuilder.must(nameMatchQueryBuilder);

相关问题