使用 elasticsearch 按营业时间过滤搜索结果

mr1*_*011 5 time filtering elasticsearch

我正在使用 elasticsearch 来索引和搜索位置,但我遇到了 1 个特定的按营业时间过滤的问题,我不知道如何解决

基本上,每个地点都有营业时间(一周中的每一天),每天可能有超过 1 个“套”的营业时间(我们现在使用 2 个)。

例如: 星期一:上午 9 点开/中午 12 点开班/下午 1 点开班/晚上 9 点关门

鉴于当前时间和当前日期,我需要搜索“开放”位置。

我不知道我应该如何将这些营业时间与位置详细信息一起编入索引,以及如何使用它们来过滤结果,任何帮助,建议将不胜感激

问候

DrT*_*ech 5

更好的方法是使用nested文档。

首先:设置映射以指定hours文档应被视为嵌套:

curl -XPUT 'http://127.0.0.1:9200/foo/?pretty=1'  -d '
{
   "mappings" : {
      "location" : {
         "properties" : {
            "hours" : {
               "include_in_root" : 1,
               "type" : "nested",
               "properties" : {
                  "open" : {
                     "type" : "short"
                  },
                  "close" : {
                     "type" : "short"
                  },
                  "day" : {
                     "index" : "not_analyzed",
                     "type" : "string"
                  }
               }
            },
            "name" : {
               "type" : "string"
            }
         }
      }
   }
}
'
Run Code Online (Sandbox Code Playgroud)

添加一些数据:(注意开放时间的多个值)

curl -XPOST 'http://127.0.0.1:9200/foo/location?pretty=1'  -d '
{
   "name" : "Test",
   "hours" : [
      {
         "open" : 9,
         "close" : 12,
         "day" : "monday"
      },
      {
         "open" : 13,
         "close" : 17,
         "day" : "monday"
      }
   ]
}
'
Run Code Online (Sandbox Code Playgroud)

然后运行查询,按当前日期和时间进行过滤:

curl -XGET 'http://127.0.0.1:9200/foo/location/_search?pretty=1'  -d '
{
   "query" : {
      "filtered" : {
         "query" : {
            "text" : {
               "name" : "test"
            }
         },
         "filter" : {
            "nested" : {
               "path" : "hours",
               "filter" : {
                  "and" : [
                     {
                        "term" : {
                           "hours.day" : "monday"
                        }
                     },
                     {
                        "range" : {
                           "hours.close" : {
                              "gte" : 10
                           }
                        }
                     },
                     {
                        "range" : {
                           "hours.open" : {
                              "lte" : 10
                           }
                        }
                     }
                  ]
               }
            }
         }
      }
   }
}
'
Run Code Online (Sandbox Code Playgroud)

这应该有效。

不幸的是,在 0.17.5 中,它抛出了一个 NPE - 这可能是一个简单的错误,很快就会被修复。我在这里为此提出了一个问题:https ://github.com/elasticsearch/elasticsearch/issues/1263

更新奇怪的是,我现在无法复制 NPE - 这个查询似乎在 0.17.5 及更高版本上都能正常工作。一定是一些暂时的故障。

克林特