首页 > 解决方案 > 弹性:搜索不得为空和其他一些条件

问题描述

尝试翻译以下搜索。本质上,message1、message2 可以有空字符串值。如果 search1Value 或 search2Value 是空字符串,我不希望为 OR 条件中存在空字符串的那部分返回任何记录。

message1 != "" and message1 = search1Value
OR 
message2 != "" and message2 = search2Value

因此,如果索引中可用文档的示例...

id, message1, message2
1, "", "abc"
2, "", ""
3, "def", ""
4, "", "ghi"

如果 searchValue1 是空字符串,而 searchValue2 是 abc 我想返回,只记录 1。不记录 1、2 和 4。

这是设置

PUT test_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "message1": {
          "type": "keyword",
          "ignore_above": 20 
        }, 
        "message2": {
          "type": "keyword",
          "ignore_above": 20 
        }
      }
    }
  }
}

数据...

PUT test_index/_doc/1 
{
  "message1": "",
  "message2": "abc"
}

PUT test_index/_doc/2 
{
  "message1": "",
  "message2": ""
}

PUT test_index/_doc/3 
{
  "message1": "def",
  "message2": ""
}

PUT test_index/_doc/4 
{
  "message1": "",
  "message2": "ghi"
}

搜索 ...

GET test_index/_search 
{
  "query": {
    "bool" : {
      "should": [{
        "bool": {
          "must": [{
            "bool": {
              "must_not": [{ 
                "term": { "message1" : "" }
              }]
            },
            "bool": {
              "must": [{
                "term": { "message1" : "" }
              }]
            }
          }]
        },
        "bool": {
          "must": [{
            "bool": {
              "must_not": [{ 
                "term": { "message2" : "" }
              }]
            },
            "bool": {
              "must": [{
                "term": { "message2" : "abc" }
              }]
            }
          }]
        }
      }]
    }
  }
}

上面的 dsl 不起作用......似乎无法让它做我想做的事。

标签: elasticsearchdsl

解决方案


看起来我做得对..但括号错了..

GET test_index/_search 
{
  "query": {
    "bool" : {
      "should": [
        {
          "bool": {
            "must": [{
              "bool": {
                "must_not": [{ 
                  "term": { "message1" : "" }
                }]
              }
            },
            {
              "bool": {
                "must": [{
                  "term": { "message1" : "" }
                }]
              }
            }]
          }
        },
        {
        "bool": {
          "must": [{
            "bool": {
              "must_not": [{ 
                "term": { "message2" : "" }
              }]
            }
          },
          {
            "bool": {
              "must": [{
                "term": { "message2" : "abc" }
              }]
            }
          }]
        }
      }]
    }
  }
}

推荐阅读