如何在elasticsearch查询中添加与或?

时间:2019-04-26 15:21:45

标签: node.js elasticsearch

我正在尝试创建一个查询,以便用户可以搜索特定产品。该查询适用于1个条件,但是当我添加另一个条件时,它将给我一个空数组。

我正在寻找使用SQL的内容:

SELECT * FROM products WHERE shop = "shop" AND  title like "%dogs%"

具有1个条件的示例

GET /products/_search?size=25&from=50
{
    "query": {
         "bool": {
             "must": [
                   {"match_phrase": {"shop": "xxxxx.myshopify.com"}}
             ]
         }
     }
 }

/ products / _mapping

{
  "products" : {
    "mappings" : {
      "properties" : {
        "body_html" : {
          ...
        },
        "created_at" : {
          "type" : "date"
        },
        "handle" : {
          ...
        },
        "id" : {
          "type" : "long"
        },
        "image" : {
          ...
        },
        "images" : {
          ...
        },
        "shop" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "title" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

以下方法可能会起作用:

GET /products/_search?size=25&from=50
{
    "query": {
         "bool": {
             "must": [
                   {"term": {"shop": "xxxxx.myshopify.com"}},
                   {"match": {"title": "dogs"}},
             ]
         }
     }
 }

答案 1 :(得分:0)

对于like部分,可以进行wildcard查询。

 {
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "shop": "xxxxx.myshopify.com"
          }
        },
        {
          "wildcard": {
            "title": {
              "value": "*dog*"
            }
          }
        }
      ]
    }
  }
}