使用 Elasticsearch 2.x 的查询上下文和过滤器上下文之间的逻辑 OR



假设我有一个具有以下映射的索引:

PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "full_text": {
          "type":  "string" 
        },
        "exact_value": {
          "type":  "string",
          "index": "not_analyzed" 
        }
      }
    }
  }
}

我索引一个简单的文档,如下所示:

PUT my_index/my_type/1
{
  "full_text":   "This is the city where I live", 
  "exact_value": "MILAN"  
}

我想要的是创建一个可以在逻辑上表示为的查询:

full_text:CONTAINS('live') OR exact_value:CONTAINS('MILAN')

但是我想在查询上下文中搜索full_text,同时exact_value在过滤器上下文中搜索

我尝试使用以下查询,但它不起作用(用罗马替换米兰是证明)

POST _search
{
  "query" : {
    "bool" : {
      "filter" : {
        "bool" : {
          "should" : {
            "term" : {
              "exact_value" : "MILAN"
            }
          }
        }
      },
      "should" : {
        "query_string" : {
          "query" : "live",
          "fields" : [ "full_text" ]
        }
      }
    }
  }
}

提前致谢

我会试试这个:

POST my_index/_search
{
  "query": {
    "bool": {
      "filter": {
        "or": [
          {
            "term": {
              "exact_value": "MILAN"
            }
          },
          {
            "term": {
              "full_text": "live"
            }
          }
        ]
      }
    }
  }
}

但是,由于您想使用过滤器,请注意您将没有评分。这意味着搜索"Live OR MILAN"将产生与"live OR ROMA"和"live"完全相同的响应

实际包含"live或MILAN"的文档可能不在第一位

尝试使用这个:

POST my_index/_search
{
"filter": {
  "bool": {
     "should": [
        {
           "term": {
              "exact_value": "MILAN"
           }
        },
        {
           "query": {
              "query_string": {
                 "default_field": "full_text",
                 "query": "live"
              }
           }
         }
       ]
     }
    }
   }

我找到了可以使用Java API构建的解决方案

{
  "query" : {
    "bool" : {
      "should" : [ {
        "bool" : {
          "filter" : {
            "term" : {
              "exact_value" : "MILAN"
            }
          }
        }
      }, {
        "query_string" : {
          "query" : "live",
          "fields" : [ "full_text" ]
        }
      } ]
    }
  }
}

最新更新