更好的方法是使用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"
}
}
}
}
}
'
添加一些数据:(注意开放时间的多个值)
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"
}
]
}
'
然后运行查询,按当前日期和时间过滤:
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
更新 奇怪的是,我现在无法复制 NPE - 这个查询似乎在 0.17.5 及更高版本上都能正常工作。一定是一些暂时的故障。
克林特