【问题标题】:Elasticsearch : filter results based on the date rangeElasticsearch:根据日期范围过滤结果
【发布时间】:2019-09-21 19:01:45
【问题描述】:

我正在使用 Elasticsearch 6.6,尝试根据在某个日期范围内传递给查询 (Bool) 的多个值 (email_address) 提取多个结果/记录。例如:我想根据他们的电子邮件地址(annie@test.com、charles@test.com、heman@test.com)和时间段(即 project_date(2019-01-01))提取有关少数员工的信息。

我确实使用了 should 表达式,但不幸的是它根据日期范围从 elasticsearch 中提取所有记录,即它甚至从 project_date 2019-01-01 中提取其他员工信息。

{

  "query": {

    "bool": {

      "should": [

        { "match": { "email_address":   "annie@test.com"        }},

        { "match": { "email_address":   "chalavadi@test.com"        }}

      ],

      "filter": [

        { "range": { "project_date": { "gte": "2019-08-01" }}}

      ]

    }

  }

}

我也尝试过必须表达,但没有得到任何结果。您能帮我找到使用日期范围内的电子邮件地址的员工吗?

提前致谢。

【问题讨论】:

  • 你能给我一个样本数据吗?那么我可以帮你。还有文档结构。

标签: elasticsearch


【解决方案1】:

Should(Or) 子句是可选的

引自this 文章。 “在查询中,如果存在 must 和 filter 查询,则 should 查询的出现有助于影响得分。但是,如果 bool 查询位于过滤器上下文中或既没有 must 也没有 filter 查询,则至少有一个 should 查询必须匹配一个文档。”

所以在您的查询中应该只影响分数而不是实际过滤文档。您必须将 should 包裹在 must 中,或者将其移动到 filter 中(如果不需要评分)。

GET employeeindex/_search
{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "projectdate": {
            "gte": "2019-01-01"
          }
        }
      },
      "must": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "email.raw": "abc@text.com"
                }
              },
              {
                "term": {
                  "email.raw": "efg@text.com"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

您也可以像@AlwaysSunny 的回答那样将 should 子句替换为 terms 子句。

【讨论】:

  • 很高兴能帮上忙
  • 我还有一个关于搜索的问题。我应该提交一个新帖子吗?
  • 是的,请,因为这里已经关闭,会尽力帮助那里
【解决方案2】:

您可以使用terms 和range 以及filter 中的现有查询以更短的方式执行此操作。由于should 子句,您现有的查询无法按预期工作,它使您的filter 更弱。 在此处阅读更多信息:

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

{
 "query": { 
 "bool": { 
   "filter": [ 
     {
          "terms": {
            "email_address.keyword": [
              "annie@test.com", "chalavedi@test.com"
            ]
          }
      },
      {
          "range": {
            "project_date": {
              "gte": "2019-08-01"
            }
          }
       }
    ]
   }
  }
}

【讨论】:

  • 我尝试了上述解决方案,但没有成功。看起来我错过了一些东西。谢谢@Always Sunny。
  • 我没有收到任何错误但没有获取记录。 ``` { "took": 0, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 0, "max_score": null, "hits": [] } } ``` 如果我遗漏了什么,请告诉我。提前致谢。
  • 我可以在 project_date 值上看到一个错字,它是 2019-08001 ,现在更正了,如果没有结果,你可以只调整 email_adress 而不是 email_address.keyword但大多数情况下,我认为由于错字而没有返回结果。结帐并让我进一步了解
  • 抱歉回复晚了,一定会立即尝试并及时通知您。
  • 好的没问题,慢慢来吧:)
猜你喜欢
  • 1970-01-01
  • 2016-11-25
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2013-08-21
  • 1970-01-01
  • 2021-01-10
相关资源
最近更新 更多