Support arbitrary combination of AND, OR, NOT in ElasticSearch


(Abhishek Vaid) #1
  • I have an application which wants to expose the API to query Arbitary AND OR NOT queries to the user. The user should be able to give me a string which any number of AND, OR and NOT phrases. The rules for nesting should be parenthesis and normal precedence rules should apply.

As an Eg.

  • query= ( (Abhishek AND Vaid) OR ( Abhishek AND Vaids) ) AND NOT (Abhishek AND Vaider) should be a valid query.

The Rules for operators are as following:

    • I'm defining three operators here:" AND "," OR ",and" NOT ". (these are AND, OR and NOT.
  • The " NOT " is unary and " AND " and " OR " is binary. " NOT " has higher precedence over other two.

Is there a way for me to do this out of the box from Java Driver in ES ? Please note that I can always convert such a query in nested boolean, but I don't want to write a lexer and parser to create a parse tree by scratch and then resolve it to a complex boolean DSL. I'm looking for some existing functionality to achieve this.


(David Pilato) #2

I guess the simple query string query or the query string query could do what you need.

Look at the doc, it comes with Lucene query syntax which is close to your needs IMHO.


(Abhishek Vaid) #3

Hi dadoonet,

  • Yes, it's perfect. However, I'm struggling with one aspect of it. I want to search for complete and exact phrases and I don't want the user to embed '"' for every combination of keyword (which is actually a phrase)

As an example:

  • (Moto G3 OR Moto X) AND (Lenovo Vibe OR Lenovo Moto) should be interpreted as "Moto G3" and "Moto X" and so on.
  • A simple query: Moto G3 2015 edition should just work as a complete phrase "Moto G3 2015 edition"

There are numerous options which are listed at this link: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html but I don't understand them fully as to use which ones for my use case.


(David Pilato) #4

I think that if your user wants to search for phrases, he will have to use ".

More details about the query syntax at https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax (But I'm sure you already saw that)


(system) #5