使用 elasticsearch 按营业时间过滤搜索结果 [英] Filtering search results by operating hour with elasticsearch
问题描述
我正在使用 elasticsearch 来索引和搜索位置,但我遇到了 1 个特定的问题,即按营业时间过滤,我不知道如何解决
I'm using elasticsearch to index and search locations, and I'm running into 1 particular issue with filtering by operating hour which I don't know how to work out
基本上,每个地点都有营业时间(一周中的每一天),每天可能有超过 1 个套"营业时间(我们现在使用 2 个).
Basically, each location will have operating hour (for every day of the week) and each day may have more than 1 "sets" of operating hour (we use 2 for now).
例如:周一:上午 9 点开门/中午 12 点关门下午1点开/晚上9点关门
For example: Monday: open 9am / close 12pm open 1pm / close 9pm
给定当前时间和当前日期,我需要搜索开放"位置.
Given the current time and the current day of the week, I need to search for the "open" locations.
我不知道我应该如何将这些营业时间与位置详细信息一起编入索引,以及如何使用它们来过滤结果,任何帮助和建议将不胜感激
I don't know how should I index these operating hour together with the location details, and how to use them to filter out the results yet, any help, suggestion would be really appreciated
问候
推荐答案
更好的方法是使用 nested
文档.
A better way to do this would be to use nested
documents.
首先:设置映射以指定 hours
文档应被视为嵌套:
First: set up your mapping to specify that the hours
document should be treated as nested:
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"
}
}
}
}
}
'
添加一些数据:(注意开放时间的多个值)
Add some data: (note the multiple values for opening hours)
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"
}
]
}
'
然后运行您的查询,按当前日期和时间过滤:
Then run your query, filtering by the current day and time:
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
}
}
}
]
}
}
}
}
}
}
'
这应该有效.
不幸的是,在 0.17.5 中,它抛出了一个 NPE - 这可能是一个简单的错误,很快就会修复.我在这里打开了一个问题:https://github.com/elasticsearch/elasticsearch/issues/1263
Unfortunately, in 0.17.5, it throws an NPE - it is likely to be a simple bug which will be fixed shortly. I have opened an issue for this here: https://github.com/elasticsearch/elasticsearch/issues/1263
更新 奇怪的是,我现在无法复制 NPE - 此查询似乎在 0.17.5 及更高版本上都能正常工作.一定是暂时的故障.
UPDATE Bizarrely, I now can't replicate the NPE - this query seems to work correctly both on version 0.17.5 and above. Must have been some temporary glitch.
克林特
这篇关于使用 elasticsearch 按营业时间过滤搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!