【问题标题】:Elastic search: exact match query on string array弹性搜索:字符串数组上的精确匹配查询
【发布时间】:2016-10-09 13:27:00
【问题描述】:

鉴于这份文件:

{"name": "Perfect Sunny-Side Up Eggs","ingredientList": ["canola oil","eggs"]}

如何在弹性搜索中构建查询以返回给定查询词“油蛋”的字符串数组的完全匹配,到目前为止,这就是我所拥有的,但它返回其他不相关的文档:

POST /recipes/recipe/_search
{
   "query": {
      "match": {
         "ingredientList": {
            "query": [
               "oil",
               "eggs"
            ],
            "operator": "and"
         }
      }
   }
}

例如,返回此文档但它不包含“油”。结果应该只包含“油”和“鸡蛋”:

{"name": "Quick Baked French Toast","ingredientList": ["butter","cinnamon raisin bread","eggs"]}

【问题讨论】:

标签: elasticsearch


【解决方案1】:

Elastic 没有用于精确匹配数组的 API。但同样可以使用两种方法实现:

  1. 使用多个 must 块(不是首选)

  2. 使用terms set查询和script

     "query": {
       "bool": {
         "must": [
           {
             "terms_set": {
               "ingredientList": {
                 "terms": ingredients,
                 "minimum_should_match_script": {
                   "source": "Math.min(params.num_terms, {})".format(len(ingredients))
                 }
               }
             }
           },
           {
             "script": {
               "script": {
                 "inline": "doc['ingredientList'].length == params.list_length",
                 "lang": "painless",
                 "params": {
                   "list_length": len(ingredients)
                 }
               }
             }
           }
         ]
       }
     }
    

【讨论】:

    【解决方案2】:

    您的查询将如下所示:

    {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "ingredientList": "oil"
              }
            },
            {
              "term": {
                "ingredientList": "eggs"
              }
            }
          ]
        }
      }
    }
    

    给我结果:

    {
      "took" : 1,
      "timed_out" : false,
      "_shards" : {
        "total" : 5,
        "successful" : 5,
        "failed" : 0
      },
      "hits" : {
        "total" : 1,
        "max_score" : 1.0,
        "hits" : [ {
          "_index" : "ingredients",
          "_type" : "recipe",
          "_id" : "AVeprXFrNutW6yNguPqp",
          "_score" : 1.0,
          "_source" : {
            "name" : "Perfect Sunny-Side Up Eggs",
            "ingredientList" : [ "canola oil", "eggs" ]
          }
        } ]
      }
    }
    

    【讨论】:

    • 非常感谢!
    • 您好,我知道这是很久以前发布的,但我正在尝试做类似的事情,除了在我的情况下它应该包含确切的短语“油”而不是“菜籽油”。你知道怎么做吗?谢谢。
    • @tomfl 你好,我也在找同样的问题,你解决了吗?
    • @Vladimir 嗯,如果我没记错的话,我不得不将分析仪更改为keywordelastic.co/guide/en/elasticsearch/reference/current/…
    • 使"oil""canola oil" 不匹配,然后说"term": { "ingredientList.keyword": "oil" }
    猜你喜欢
    • 2018-08-02
    • 2020-03-06
    • 2015-08-02
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多