Java API中的Elasticsearch嵌套查询

f0ofjuux  于 2022-12-03  发布在  ElasticSearch
关注(0)|答案(1)|浏览(145)

我刚接触Elasticsearch和Java。我正在尝试转换一个嵌套的Elasticsearch查询,它同时有“必须”和“应该”函数。有人能帮上忙吗?

GET /list/_search
{
  "size": 12,
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "multi_match": {
                  "query": "city hed",
                  "type": "bool_prefix",
                  "fields": [
                    "cityName":"",
                    "countryCodeName":"",
                    "iso":""
                  ]
                }
              },
              {
                "multi_match": {
                  "query": "city hed",
                  "fuzziness": "AUTO",
                  "fields": [
                    "cityName*"
                    ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "iso": ""
                }
              },
              {
                "match": {
                  "iso": ""
                }
              }
            ]
          }
        }
      ]
    }
  }
}

我需要它的方法逻辑,就像在JavaAPI中一样

t3irkdon

t3irkdon1#

如果使用Java High Client,请尝试以下操作:

SearchRequest searchRequest = new SearchRequest("idx_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

MultiMatchQueryBuilder matchQueryBuilder = QueryBuilders
    .multiMatchQuery("city hed")
    .type(Type.PHRASE_PREFIX)
    .field("cityName")
    .field("countryCodeName")
    .field("iso");

MultiMatchQueryBuilder matchQueryBuilder2 = QueryBuilders
    .multiMatchQuery("city hed")
    .fuzziness("2")
    .field("cityName*");

MatchQueryBuilder matchQuery01 = QueryBuilders.matchQuery("iso", "");
MatchQueryBuilder matchQuery02 = QueryBuilders.matchQuery("iso", "");

BoolQueryBuilder bool01 = QueryBuilders.boolQuery().should(matchQueryBuilder).should(matchQueryBuilder2);
BoolQueryBuilder bool02 = QueryBuilders.boolQuery().should(matchQuery01).should(matchQuery02);

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().must(bool01).must(bool02);

searchSourceBuilder.query(boolQueryBuilder);

searchRequest.source(searchSourceBuilder);

SearchResponse searchResponse = getClient().search(searchRequest, RequestOptions.DEFAULT);

相关问题