开发者学堂课程【ElasticSearch 入门精讲:boolQuery】学习笔记,与课程紧密连接,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/631/detail/10004
boolQery
内容介绍:
一、讲义
二、演示
一、讲义
组合查询(复杂查询)
must(QueryBuilders): AND
mustNot(QueryBuilders): NOT
should(QueryBuilders):OR
在定义 json:放置到 Elasticsearch的插件中
{
"query":{
"bool":{
"must":{
"term":{
"title":"elasticsearch"
}
},
"should":{
"range":{
"id":{
"from":1,
"to":2
}
}
SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
.setQuery(QueryBuilders.boolQuery().must(QueryBuilderstermQuery("title","搜索").must(QueryBuilders.wildcardQuery("content","elagic*ch")).get();
SearchHits hits = searchResponse.getHits();//获取命中次数,查询结果有多少对象
二、演示
/**
* boolQuery 演示
*需求:查询索引库 bigdata 中的 type 之 product 中,name 为 hadoop,且 author 中包含了辛格的索引信息。
*/
@Test
public void testBoolQuery(){
//检索
SearchResponse response = client.preparesearch(INDEX)
.setTypes (TYPE)
.setQuery(QueryBuilders.boolQuery
()
.must(QueryBuilders.matchPhraseQuery(name: "name",value: "hadoop"))
.should(QueryBuilders.wildcardQuery(name: "author",query:"Sp*")))
.get();
//显示检索到的信息
SearchHits hits = response.getHits();
for (SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
}
运行结果如图
要显示检索信息为施瓦辛格,修改代码
.should(QueryBuilders.wildcardQuery(name: "author",query:"Sp*")))
为
.should(QueryBuilders.matchPhraseQuery(name: "author",query:"Spark")))
运行结果如图
如要显示两条记录,则应该将 must 都换为 should,为或的关系,
.should(QueryBuilders.matchPhraseQuery(name: "name",value: "hadoop"))
如图