Es fuzzy query problem

When I encountered es query today, I encountered some difficulties, and it took me a long time to find the cause of the problem.

The requirement is: ES implements fuzzy query. Equivalent to SQL like % like % But in the development process, I used all kinds of participles, all kinds of query code, always can’t achieve.

Question:

For example: I query sliced bread can be queried, but I query sliced bread can not be queried.

The reason is that ES adopts the word segmentation mechanism by default. As a result, when I query, the sliced bread is not included in a word segmentation, so I cannot query it.

MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
//        Iterable<Commodity> iterable = commodityRepository.search(matchQueryBuilder);
//        Iterable<Commodity> iterable = commodityRepository.search(matchQueryBuilder);
//        iterable.forEach(e->list.add(e));Copy the code

After querying the data, I tested the following code:

WildcardQueryBuilder  wildcardQueryBuilder = QueryBuilders.wildcardQuery("name", "*"+name+"*");
Iterable<Commodity> iterable = commodityRepository.search(wildcardQueryBuilder);Copy the code

We tested it. It doesn’t work. In the depressed.

Field word divider

And then I add the word divider to the field property. Delete the data on es first, and then reinsert the data.

@Field(type = FieldType.Text, analyzer = "ik_max_word") private String title; / / titleCopy the code

Testing the above two codes, still can not query the bread cutting data.

Finally, I tried dropping the entire index and re-inserting the data to test it out

DELETE /commodityCopy the code

The entire command is the delete index command in Kibaba. I then set the field properties to keyword:

@Field(type = FieldType.Keyword)
    private String name;Copy the code

Then, re-insert the data and execute with fuzzy query code:

WildcardQueryBuilder  wildcardQueryBuilder = QueryBuilders.wildcardQuery("name", "*"+name+"*");
Iterable<Commodity> iterable = commodityRepository.search(wildcardQueryBuilder);Copy the code

Miraculously, it worked. Whatever I query, as long as it contains, I can query it. It was a relief to finally solve the problem.

conclusion

When you changed the index (document) attribute, it was text, then keyword. So must first delete clean index, re – insert data in fuzzy query. My reason is that I did not delete the index. Remember to regenerate the index to achieve the fuzzy query effect.

The above content is my point of view, welcome everyone to criticize and guide, we discuss together!