Search code examples
javaelasticsearchelasticsearch-java-api

Can I search by multiple fields using the Elastic Search Java API?


Example:

|studentname | maths | computers |
++++++++++++++++++++++++++++++++++
|s1          |78     |90         |
==================================
|s2          |56     |75         |
==================================
|s3          |45     |50         |
==================================

The above table represents data that is present in Elasticsearch.

Consider that the user enters 60 and above then Elasticsearch should be able to display only s1, because he is the only student who has scored more than 60 in both subjects.

How do I solve it using Java API?

NOTE: I was able to find out for individual subjects by:

    QueryBuilder query = QueryBuilders.boolQuery()
            .should(
                     QueryBuilders.rangeQuery(maths)
                    .from(50)
                    .to(100)
            )

Solution

  • You can have multiple .should() clauses in the the bool query. So in your case:

    QueryBuilder query = QueryBuilders.boolQuery()
            .should(
                     QueryBuilders.rangeQuery(maths)
                    .from(61)
                    .to(100)
            )
            .should(
                     QueryBuilders.rangeQuery(computers)
                    .from(61)
                    .to(100)
            )
    

    Note:

    1. RangeQueryBuilder (returned from QueryBuilders.rangeQuery()) also has the method #gte().

    2. According to the docs: "In a boolean query with no must or filter clauses, one or more should clauses must match a document." So if you have have no filter or must, you might not get the desired behavior. The above answer assumes you are using some other clauses. The point is you can combine clauses in the bool query. With the Java API this just means using the clause repeatedly.

    3. You might want to use filter instead of should. This will lead to faster execution and caching (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html)