将ElasticSearch布尔查询转换为Java

4urapxun  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(170)
GET feeds/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "comment",
            "query": { 
              "match": {
                "comment.c_text": "This is mateen"
              }
            },"inner_hits": {}
          }
        },
        {
          "term": {
            "title.keyword": {
              "value": "This is mateen"
            }
          }
        },
        {
          "term": {
            "body.keyword": {
              "value": "This is mateen"
            }
          }
        }
      ]
    }
  }
}

Map如下所示:

PUT feeds
{
  "mappings": {
    "properties": {
      "comment":{
        "type": "nested"
      }
    }
  }
}

我使用的是Elasticsearch 7.17.3.为了在我的springboot中搜索Elasticsearch的所有文档,我编写了下面的代码,它给了我确切的输出:

public  List<feed> searchAllDocuments() throws IOException {
        SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
        SearchResponse searchResponse = elasticsearchClient.search(searchRequest, feed.class);
        List<Hit> hits = searchResponse.hits().hits();
        List<feed> feeds = new ArrayList<>();
        feed f=null;
        for (Hit object : hits) {
            f = (feed) object.source();
           
            feeds.add(f);
            }

        return feeds;
        }

有谁能帮我把查询转换成springboot应用程序吗?我是新手,需要你的指导

myzjeezk

myzjeezk1#

如果您使用新的Java API客户端,请尝试以下代码:

Query nestedQuery = NestedQuery.of(nq ->
    nq.path("comment")
        .innerHits(InnerHits.of(ih -> ih))
        .query(MatchQuery.of(mq -> mq.field("comment.c_text").query("This is mateen"))._toQuery())
)._toQuery();

Query termQueryTitle = TermQuery.of(
    tq -> tq.field("title.keyword").value("This is mateen")
)._toQuery();

Query termQueryBody = TermQuery.of(
    tq -> tq.field("body.keyword").value("This is mateen")
)._toQuery();

Query boolQuery = BoolQuery.of(bq -> bq.should(nestedQuery, termQueryBody, termQueryTitle))._toQuery();

SearchRequest searchRequest = SearchRequest.of(
    s -> s.index("idx_name").query(boolQuery)
);

var response = client.search(searchRequest, Feed.class);

相关问题