As a newcomer, I often encounter some problems when using elastic search. Today, the problem is: when using elastic search to search Chinese, there is no return result?
The problem is described as follows:
1. Viewing the contents of the log on kibana can be searched in Chinese, as shown in the following figure:
However, when I use Chinese to query in my code, it will only return empty. The code used in the query is as follows:
/** * Execution search * * @param queryBuilder * @param indexname * @param type * @return */ public void searcher(QueryBuilder queryBuilder, String indexname,String type) { SearchRequestBuilder srbuilder = client.prepareSearch(indexname) .setTypes(type) .setQuery(queryBuilder) .addHighlightedField("*") .setHighlighterRequireFieldMatch(false) .setFrom(0) .setSize(1000) .setExplain(true); SearchResponse searchResponse = srbuilder.execute().actionGet(); //Print query body System.out.println("--->"+srbuilder.toString()); //Print the return result System.out.println(">>>>"+searchResponse.toString()); SearchHits hits = searchResponse.getHits(); System.out.println("Query the number of records=" + hits.getTotalHits()); } public static void main(String[] args) throws IOException { ElasticSearchHandler esHandler = new ElasticSearchHandler(); // query criteria String type = "system"; String indexname = "logstash-2016-06-11"; QueryBuilder queryBuilder = QueryBuilders.termQuery("message", "test"); BoolQueryBuilder bool = QueryBuilders.boolQuery(); bool.must(queryBuilder); esHandler.searcher(bool, indexname,type); }
Query body:
Return results:
What is the reason? After searching on the Internet for a long time without any result, I can only find out by myself, and finally find out the cause of the problem under the hardship of the landlord.
The reason for the problem is simple: the default IK segmenter in elastic search cuts every Chinese word, so you want to look up the whole word directly, or the whole sentence has no result to return.
Find the reason, then the solution is simple, just need to query, first you want to query the content into one word to form a query body, and then combined together, as shown below.
public static void main(String[] args) throws IOException { ElasticSearchHandler esHandler = new ElasticSearchHandler(); // query criteria String type = "system"; String indexname = "logstash-2016-06-11"; QueryBuilder queryBuilder = QueryBuilders.termQuery("message", "measure"); QueryBuilder queryBuilder2 = QueryBuilders.termQuery("message", "try"); BoolQueryBuilder bool = QueryBuilders.boolQuery(); bool.must(queryBuilder); bool.must(queryBuilder2); esHandler.searcher(bool, indexname,type); }
This query body:
Query results:
If there are more and better solutions, you are welcome to exchange ideas in the comments section. Thank you.