简体   繁体   中英

How to put multiple match query inside a bool query in elasticsearch

I am trying to implement below elasticsearch query

{
"query": {
    "bool": {
        "must": [
            {"match": {"collegeName": "XXXX"}},
            {"match": {"userType": "STUDENT"}},
            {"match": {"details.blocklisted":"TRUE"}}
            ]
    }
}

}

How do I implement it in java. I thought of doing this

BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    searchSourceBuilder.query(boolQueryBuilder.must(new 
MatchQueryBuilder("collegeName",loggedInUserCollegeName)).must(new MatchQueryBuilder("userType",studentsSearchRequestDTO.getUserType())).must(new MatchQueryBuilder("details.blocklisted",studentsSearchRequestDTO.isBlockListed())));

Is there a better way to do???? Help!!

you can use MultiMatchQueryBuilder something like

SearchQuery searchQuery = new NativeSearchQueryBuilder()
              .withQuery(multiMatchQuery("college")
                .field("collegeName")
                .field("userType")
                .type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
              .build();

Yes,

Use Search Template ( ES official doc ). It's like a stored procedure. A query with a replaceable variable. Plus changing the query is just a simple update. Create template beforehand (POST /_search/template/templateName {BODY} ) then you can call it (POST /twitter/tweet/_search/templateName {BODY containing dynamic variables}).

similarly in JAVA

Map<String, Object> params = new HashMap<String, Object>();
params.put("search_term", "elasticsearch");
params.put("since", "now-30d");

Template template = new Template("tweets", ScriptService.ScriptType.FILE, 
MustacheScriptEngineService.NAME, null, params);
SearchRequestBuilder request = 
client.prepareSearch(INDEX).setTemplate(template);

SearchResponse response = request.execute().actionGet();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM