文章目录
1 环境准备
- 新建一个索引库item
PUT item
{
"mappings":{
"properties":{
"id":{
"type":"long"
},
"title":{
"type":"text",
"analyzer":"ik_max_word"
},
"content":{
"type":"text",
"analyzer":"ik_max_word"
},
"price":{
"type":"float"
},
"category":{
"type":"keyword"
}
}
}
}
- 插入数据
PUT item/_doc/1
{
"id":1,
"title":"小米手机",
"content":"手机中的性价比之王",
"price":1000.00,
"category":"手机"
}
PUT item/_doc/2
{
"id":2,
"title":"小米电视",
"content":"电视中的性价比之王",
"price":1005.00,
"category":"电视"
}
PUT item/_doc/3
{
"id":3,
"title":"华为电视盒子",
"content":"电视盒直播网络机顶盒4K高清华为海思芯片机顶盒WIFI宽带电视盒子家用电视合猫播放器",
"price":1005.00,
"category":"电视"
}
PUT item/_doc/4
{
"id":4,
"title":"海信冰箱",
"content":"食品保险冷冻首先农品",
"price":3005.00,
"category":"冰箱"
}
PUT item/_doc/5
{
"id":5,
"title":"华为手机",
"content":"首款5g手机",
"price":4005.00,
"category":"手机"
}
2 布尔查询(bool)
bool把各种其它查询通过must(与)、must_not(非)、should(或)的方式进行组合
- must:必须出现在匹配文档中,并且会影响匹配得分
- filter:必须出现在匹配文档中,匹配得分将会被忽略(filter不会影响得分)
- should:应该出现在匹配文档中,在布尔查询中,如果没有must或filter子句,文档必须匹配一个或者多个should子句。应该匹配的should子句的最小数量可以通过
minimum_should_match参数进行设置 - must_not:不能出现在匹配的文档中。
布尔查询采取匹配的越多越好的方式,每个匹配的子句的得分都会被加在一起,为每个文档提供最终得分(_score)
演示
比如要搜手机,价格必须在1000到20000,是否支持5g均可,品牌为华为
GET item/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"category": "手机"
}
},
{
"range": {
"price": {
"gte": 1000,
"lte": 20000
}
}
}
],
"should": [
{
"match": {
"content": "5g"
}
}
],
"filter": {
"term": {
"title": "华为"
}
}
}
}
}
GET item/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"category": "手机"
}
},
{
"range": {
"price": {
"gte": 1000,
"lte": 20000
}
}
}
],
"should": [
{
"match": {
"content": "5g"
}
}
],
"filter": {
"term": {
"title": "华为"
}
}
}
}
}
如果去掉filter:
GET item/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"category": "手机"
}
},
{
"range": {
"price": {
"gte": 1000,
"lte": 20000
}
}
}
],
"should": [
{
"match": {
"content": "5g"
}
}
]
}
}
}
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 7.009481,
"hits" : [
{
"_index" : "item",
"_type" : "_doc",
"_id" : "5",
"_score" : 7.009481,
"_source" : {
"id" : 5,
"title" : "华为手机",
"content" : "首款5g手机",
"price" : 4005.0

最低0.47元/天 解锁文章
628

被折叠的 条评论
为什么被折叠?



