弹性:搜索“不得为空”和其他一些条件

时间:2018-12-07 22:42:49

标签: elasticsearch dsl

尝试翻译以下搜索。本质上,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无法正常工作...似乎无法使其执行我想要的操作。

1 个答案:

答案 0 :(得分:0)

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

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" }
              }]
            }
          }]
        }
      }]
    }
  }
}