
ElasticSearch联合查询定义
在实际应用当中,有时候需要在多个字段上查询多种多样的文本,为了构建类似的高级查询,你需要一种能够将多查询组合成单一查询的查询方法。
这种多条件联合查询,我们叫做联合查询,也叫组合查询。
ElasticSearch联合查询语法
ElasticSearch多条件联合查询,主要采用bool查询,bool查询可以将任意多个简单查询组装在一起。
bool的语法:
{
"query": {
"bool": {
"must": [{},...], //相当于AND
"must_not": [{},...], //相当于NOT
"should": [{},...], //相当于OR
"filter": [{},...] //过滤模式
}
}
}
有四个关键字可供选择:
1)must
文档必须匹配 must 选项下的查询条件,相当于”AND”。
2)must_not
文档必须不满足 must_not 选项下的查询条件,相当于”NOT”。
2)should
文档可以匹配 should 下的查询条件,也可以不匹配,相当于OR”。
4)filter
类似于 must,但是 filter 不评分,只是过滤数据。
ElasticSearch联合查询示例
1.示例一
我要查询书籍中,名字(name)包含:java,以及信息(info)含有“mikechen互联网架构”的书籍。
ElasticSearch联合查询,示例如下:
GET books/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"name": {
"value": "java"
}
}
}
],
"should": [
{
"match": {
"info": "mikechen互联网架构"
}
}
]
}
}
}
2.示例二
实现:查询考试成绩是60分,或90分的女生。
示例如下:
GET student/_search
{
"query": {
"bool": {
"must": [
{"term": {"sex": {"value": "女"}}},
{
"bool": {
"should": [
{"term": {"score": {"value": "60"}}},
{"term": {"score": {"value": "90"}}}
]
}
}
]
}
}
}
mikechen睿哥
10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。