Create Elasticsearch terms query in Java using the Query DSL package.

huangapple go评论76阅读模式
英文:

create elastic search terms query in java using query_dsl package

问题

Here is the translated code:

import co.elastic.clients.elasticsearch._types.query_dsl.*;

BoolQuery.Builder mainQuery = QueryBuilders.bool();

BoolQuery.Builder subQuery = QueryBuilders.bool();
subQuery.should(QueryBuilders.wildcard().field("projectNumber").value('*' + projectNumber + '*'));
subQuery.should(org.elasticsearch.index.query.QueryBuilders.termsQuery("projects", projectNumber));
mainQuery.must(subQuery);

It seems you are having issues with the .toQuery() method in the termsQuery. You can directly pass the termsQuery without using .toQuery().

英文:
import co.elastic.clients.elasticsearch._types.query_dsl.*;
                     *
                     *


BoolQuery.Builder mainQuery = QueryBuilders.bool();
                     *
                     *
                     *
 //          existing logic, which cannot be changed
                     *
                     *
BoolQuery.Builder subQuery = QueryBuilders.bool();
subQuery.should(QueryBuilders.wildcard().field("projectNumber").value('*' + projectNumber + '*').build()._toQuery());
subQuery.should(org.elasticsearch.index.query.QueryBuilders.termsQuery("projects", projectNumber).toQuery());
mainQuery.must(subQuery.build()._toQuery());

I have saved a document in the elastic search and it contains the field "projectNumber" and a list "projects". Both are strings and I want to select all the documents if the project number is equal to the field "projectNumber" or it is present in the list "projects". the above-mentioned code has an issue. the ".toQuery()" method in "termsQuery" gives compilation error, "Cannot access org.apache.lucene.search.Query". and if I remove the ".toQuery()" i will get "Cannot resolve method 'should(TermsQueryBuilder)'" error.

Can anyone help? if the above-mentioned TermsQuery declaration is not possible is it possible to declare the terms query like "TermsQuery.Builder termsQuery = QueryBuilders.terms();"?

答案1

得分: 0

我能够按如下方式编写TermQuery:

TermsQueryField numberField = new TermsQueryField.Builder()
 .value(List.of(projectNumber).stream().map(FieldValue::of).collect(Collectors.toList()))
 .build();

subQuery.should(QueryBuilders.terms(term -> term.field("projects").terms(numberField)));
英文:

I was able to write the TermQuery as follows,

TermsQueryField numberField = new TermsQueryField.Builder()
 .value(List.of(projectNumber).stream().map(FieldValue::of).collect(Collectors.toList()))
 .build();

subQuery.should(QueryBuilders.terms(term -> term.field("projects").terms(numberField)));

huangapple
  • 本文由 发表于 2023年5月17日 14:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定