bool query
布尔查询是一个复合查询,由各个bool类型的子查询组成。
- must :返回文档必须满足该条件,且提供分数
- filter :返回文档必须满足该条件,但是不需要提供分数
- should :返回文档可以满足0个或多个条件,且提供分数
- must_not : 返回文档必须不满足条件,但是不需要提供分数
1.must子语句
且逻辑
GET myindex/_search
{
"query": {
"bool": {
"must" :{
"term" :{
"name" : "mahuateng"
}
}
}
}
}
GET myindex/_search
{
"query": {
"bool": {
"must" : [
{
"term" :{
"name" : "mahuateng"
}
}
]
}
}
}
返回结果:(有具体得分)
"hits": [
{
"_index": "myindex",
"_type": "mytype",
"_id": "2",
"_score": 0.6931472,
"_source": {
"name": "mahuateng",
"age": "40",
"addr": "zhongguo guangdong shenzhen",
"city": "shenzhen"
}
}
]
2.filter子语句
且逻辑
GET myindex/_search
{
"query": {
"bool": {
"filter" :{
"term" :{
"name" : "mahuateng"
}
}
}
}
}
GET myindex/_search
{
"query": {
"bool": {
"filter" : [
{
"term" :{
"name" : "mahuateng"
}
}
]
}
}
}
返回结果:(等分为0)
"hits": [
{
"_index": "myindex",
"_type": "mytype",
"_id": "2",
"_score": 0,
"_source": {
"name": "mahuateng",
"age": "40",
"addr": "zhongguo guangdong shenzhen",
"city": "shenzhen"
}
}
]
}
3.must_not子语句
非逻辑
GET myindex/_search
{
"query": {
"bool": {
"must_not" :{
"term" :{
"name" : "mahuateng"
}
}
}
}
}
GET myindex/_search
{
"query": {
"bool": {
"must_not" : [
{
"term" :{
"name" : "mahuateng"
}
}
]
}
}
}
返回结果:(得分都是1)
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "myindex",
"_type": "mytype",
"_id": "3",
"_score": 1,
"_source": {
"name": "xiaoyu",
"age": "30",
"addr": "中国安徽亳州",
"city": "shenzhen"
}
}
]
}
4.should子语句
或逻辑(or)
GET myindex/_search
{
"query": {
"bool": {
"should": [
{
"range": {
"age": {
"gt": "90",
"lt": "100"
}
}
},
{
"range": {
"age": {
"lt": "20"
}
}
}
],
"minimum_should_match": 0
}
}
}
minimum_should_match 控制文档最小满足几个条件。
综合例子
GET myindex/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"name": {
"value": "mahuateng"
}
}
}
],
"filter" : {
"match": {
"addr": "zhongguo"
}
},
"should": [
{
"range": {
"age": {
"gt": "90"
}
}
},
{
"range": {
"age": {
"lt": "10"
}
}
}
],
"minimum_should_match": 0
}
}
}
返回结果:
"hits": [
{
"_index": "myindex",
"_type": "mytype",
"_id": "2",
"_score": 0.6931472,
"_source": {
"name": "mahuateng",
"age": "40",
"addr": "zhongguo guangdong shenzhen",
"city": "shenzhen"
}
}
]
注意上面返回文档并不满足should逻辑,但是依然返回。为了避免这种情况出现可以设置minimum_should_match 为1。这样可以得到符合其中一个年龄的用户了,本例子就是没有结果返回。
|