Support arbitrary combination of AND, OR, NOT in ElasticSearch

  • 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.

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.

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: but I don't understand them fully as to use which ones for my use case.

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

More details about the query syntax at (But I'm sure you already saw that)