elasticsearch代码中如何处理搜索匹配空字符串""

使用java代码搜索ES直接匹配""并不能匹配到空字符串,如:

			BoolQueryBuilder mustNot = QueryBuilders.boolQuery()
					.must(QueryBuilders.existsQuery("desc"))
					.mustNot(QueryBuilders.termQuery("desc", ""))
					.mustNot(QueryBuilders.termQuery("desc","null"));

原因是:field字段为text类型时,会默认进行分词,对于“空字符串”,索引时默认不进行倒排索引,因此查不到结果

查遍全网都没有合适的方法,有的说给text字段设置第二参数keyword,如:

PUT /accounts/_mapping/person/
{
  "properties": {
        "desc": {
          "type": "text",
          "analyzer": "ik_max_word",
          "fielddata": true,
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
  }
}

但实际并不能奏效,而官网给出的方法:

"null_value":"NULL",

同样不能解决问题。

重点来了,我想到了空字符串就是任意非空字符串的对立面,于是想到通配符*,而配合使用支持通配符的wildcard查询终于成功地解决的空字符串匹配的问题,代码如下:

			BoolQueryBuilder notNull = QueryBuilders.boolQuery()
					.must(QueryBuilders.existsQuery("desc"))
					.must(QueryBuilders.wildcardQuery("desc", "*"));
//附带统计count的代码:
			AggregationBuilder agg = AggregationBuilders.filter("filter",notNull);
			SearchResponse response = client.prepareSearch("accounts").addAggregation(agg).execute().actionGet();
			Filter filter = response.getAggregations().get("filter");
			System.out.println(filter.getDocCount());

依赖为:

    
        org.elasticsearch.client
        transport
        6.5.2
    
        
        org.elasticsearch
        elasticsearch
        6.5.2
    

 

你可能感兴趣的:(elasticsearch代码中如何处理搜索匹配空字符串"")