A better way to do this would be to use nested
documents.
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
}
}
}
]
}
}
}
}
}
}
'
This should work.
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
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.
clint
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…