大数据技术之Elasticsearch-Java API操作(二)条件查询QueryBuilder
模糊查询(fuzzy)
注意:需要加入分词器,不然容易搜不到匹配的词
@Test public void fuzzy() {
// 1 模糊查询 SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article") .setQuery(QueryBuilders.fuzzyQuery("title", "lucene")).get();
// 2 打印查询结果 SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象 System.out.println("查询结果有:" + hits.getTotalHits() + "条");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) { SearchHit searchHit = iterator.next(); // 每个查询对象
System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印 }
// 3 关闭连接 client.close(); } |
****自己操作****
Java代码:
// 十二、模糊查询-fuzzy // 注意:需要加入分词器,不然容易搜不到匹配的词
@Test public void fuzzyQuery() { // 模糊查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article") .setQuery(QueryBuilders.fuzzyQuery("content", "web")).get(); SearchHits hits = searchResponse.getHits(); System.out.println("查询结果有:" + hits.getTotalHits() + " 条"); for (SearchHit searchHits : hits) { System.out.println(searchHits.getSourceAsString()); } client.close(); }
结果:
查询结果有:4 条
{"id":5,"title":"基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口"}
{"id":"1","title":"基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口"}
{"id":3,"title":"基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口"}
{"id":"2","title":"基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。大数据前景无限","createDate":"2017-8-22"}