Search code examples
javaelasticsearchelasticsearch-java-api

Bool query with fuzziness in elastic search java client


I am trying to implement the selection of users from a given college and name. Here the name has fuzzy query. Following is the query in elastic search (v5.1.2) which gives me the desired result. But gives an error in Java

{
    "query" : {
        "bool": {
            "must" : [{
                "match": {
                    "collegeAccountCode": "DIT"
                }
            },
            { 
                "match": {
                    "name" : {
                        "query": "Rahul",
                        "fuzziness" : "AUTO"
                    }
                }
            }]
        }
    }
}

I tried to implement this using following java API (v5.1.2)

QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name", studentName).fuzziness())
            .must(QueryBuilders.matchQuery("collegeAccountCode", AccountId));

But I get an error saying :

"The method must(QueryBuilder) in the type BoolQueryBuilder is not applicable for the arguments 
 (Fuzziness)"

How to fix this error or is there any other way to implement this query ?


Solution

  • The problem is, that method fuziness() without parameter return the current Fuzziness, which is obviously isn't expected by must(), and you need to do something like this:

    QueryBuilders.boolQuery()
                    .must(QueryBuilders.matchQuery("name", "Rahul").fuzziness(Fuzziness.AUTO))
                    .must(QueryBuilders.matchQuery("collegeAccountCode", "DIT"));
    

    A piece of code, explaining the problem a bit more:

     /** Sets the fuzziness used when evaluated to a fuzzy query type. Defaults to "AUTO". */
        public MatchQueryBuilder fuzziness(Object fuzziness) {
            this.fuzziness = Fuzziness.build(fuzziness);
            return this;
        }
    
        /**  Gets the fuzziness used when evaluated to a fuzzy query type. */
        public Fuzziness fuzziness() {
            return this.fuzziness;
        }
    

    You called, the second method, while you need to call the first one.