ElasticSearch類似Mysql的not in 和 in 查詢

zhaozhangxiao發表於2021-09-08

ElasticSearch 的IN查詢

//查詢資料在goods_id為[1,2,3]的所有資料,類似Mysql IN (1,2,3)
{
 "query":{
    "bool": {
    "must": [
        {
            "match_all":{}
        }, 
        {
            "terms": {
                "goods_id": [1,2,3]
            }
        }
        ]
    }

  }
}


//匹配查詢多數用在商城首頁商品搜尋(推薦)

{
    "from": 0,
    "query": {
        "bool": {
            "must": [{
                "multi_match": {
                    "fields": ["goods_name", "brand"],
                    "query": "北京測試商品001-3",
                    "type": "most_fields"
                }
            }]
        }
    },
    "size": 100,
    "sort": {        
      "price": {
            "order": "desc"
        },
        "views": {
            "order": "desc"
        }
    }
}

ElasticSearch 的 NOT IN 查詢

//查詢資料不在goods_id為[1,2,3]的所有資料,類似Mysql NOT IN (1,2,3)
{
 "query":{
    "bool": {
    "must": [
        {
            "match_all":{}
        }
        ]
    },
    "must_not"[
            {
            "terms": 
                {
                    "goods_id": [1,2,3]
                }
            }]
        }
    ]
  }
}

 ElasticSearch 分頁、排序以及多欄位匹配查詢

//分頁、排序以及多欄位匹配查詢,fields為查詢關鍵詞需要匹配的欄位;query關鍵詞;type查詢型別 most_fields總體算分最高的
{
    "from": 0,
    "query": {
        "bool": {
            "must": [{
                "multi_match": {
                    "fields": ["goods_name", "brand"],
                    "query": "北京測試商品001-3",
                    "type": "most_fields"
                }
            }, 
            {
                "terms": {
                    "goods_id": [6]
                }
            }]
        }
    },
    "size": 100,
    "sort": {
        "mall_sort_order": {
            "order": "desc"
        },
        "sales": {
            "order": "desc"
        }
    }
}

 ElasticSearch 按照單個欄位算分從高到低進行排序


{
    "from": 0,
    "query": {
        "bool": {
            "must": [{
                "multi_match": {
                    "fields": ["goods_name", "brand"],
                    "query": "神經系統",
                    "type": "best_fields"
                }
            }]
        }
    },
    "size": 100,
    "sort": {
      "_score":{
            "order": "desc"
      }
    }
}
等同於
POST dev_shop_index/_search
{
 "query":{
  "dis_max" : {
   "queries":[
    {
     "match":{
      "goods_name" : "神經系統"
     }
    },
    {
     "match" : {
      "brand" : "神經系統"
     }
    }
    }
   ]
  }
 }
}

等同於
{
  "query": {
    "multi_match": {
        "fields": ["goods_name", "brand"],
        "query": "神經系統",
        "type": "best_fields"
    }
  } 
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章