OR and AND in Elasticsearch request

I have several json documents with the following format: -

_source: { userId: "A1A1", customerId: "C1", component: "comp_1", timestamp: 1408986553, } 

I want to request a document based on the following: -

 (( userId == currentUserId) OR ( customerId== currentCustomerId) OR (currentRole ==ADMIN) ) AND component= currentComponent) 

I tried using SearchSourceBuilder and QueryBuilders.matchQuery, but I could not put a few subqueries with the AND and OR statements.

 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("userId",userId)).sort("timestamp", SortOrder.DESC).size(count); 

How do we query elasticsearch using the OR and AND operators?

+6
source share
2 answers

I think in this case the best Bool request is the best snapshot.

Sort of:

 { "bool" : { "must" : { "term" : { "component" : "comp_1" } }, "should" : [ { "term" : { "userId" : "A1A1" } }, { "term" : { "customerId" : "C1" } }, { "term" : { "currentRole" : "ADMIN" } } ], "minimum_should_match" : 1 } } 

What gives in Java:

 QueryBuilder qb = QueryBuilders .boolQuery() .must(termQuery("component", currentComponent)) .should(termQuery("userId", currentUserId)) .should(termQuery("customerId", currentCustomerId)) .should(termQuery("currentRole", ADMIN)) .minimumShouldMatch("1"); // or .minimumNumberShouldMatch(1) 

Parts must AND s, parts should larger or smaller than OR s, except that you can specify the minimum number of should to match (using minimum_should_match ), this is at least 1 by default, I think (but you can set it to 0, and this means that a document that does not meet the should condition will be returned).

If you want to perform more complex queries involving nested AND and OR s, simply insert other bool queries inside the must or should parts.

In addition, since you are looking for exact values ​​(ids, etc.), perhaps you can use terminal queries instead of query matches , which will save you from analysis (if these fields are parsed at all, which does not necessarily make sense for identifiers). If they are analyzed, you can still do it, but only if you know exactly how your conditions are stored (a standard analyzer stores them below, for example, ).

+25
source

If you use query_string , your AND and OR will be interpreted as such by the Lucene library.

It allows you to search

 (currentUserId OR currentCustomerId) AND currentComponent 

eg. By default, values ​​will be found in all fields.

+2
source

Source: https://habr.com/ru/post/974494/


All Articles