我正在尝试创建一个查询,该查询返回在该日期(或日期范围)没有预订的可用产品或根本没有预订。这让我发疯了。
这是我当前的索引设置映射:
{
"development_product_instances" : {
"aliases" : { },
"mappings" : {
"product_instance" : {
"properties" : {
"reservations" : {
"type" : "nested",
"properties" : {
"end_date" : {
"type" : "date",
"format" : "yyyy-MM-dd"
},
"start_date" : {
"type" : "date",
"format" : "yyyy-MM-dd"
}
}
}
}
}
},
"settings" : {
"index" : {
"creation_date" : "1503327829680",
"number_of_shards" : "5",
"number_of_replicas" : "1",
"uuid" : "9b9BhF-ITta2dlCKRLrnfA",
"version" : {
"created" : "2040499"
}
}
},
"warmers" : { }
}
}
查询:
{
bool: {
should: [
{
nested: {
path: "reservations",
filter: {
bool: {
must_not: [
{
range:
{
"reservations.start_date":
{
gte: start_date,
lte: end_date
}
}
},
{
range:
{
"reservations.end_date":
{
gte: start_date,
lt: end_date
}
}
}
]
}
}
}
},
{
not: {
nested: {
path: "reservations",
filter: {
match_all: {}
}
}
}
}
]
}
}
当有多个预订时,它会全部返回。
我希望有人能看到那里的错误。也许我在大局中遗漏了一些东西。
答案 0 :(得分:1)
您的问题是must_not
位于nested
查询中。这意味着如果它匹配任何嵌套预订,则父文档匹配。因此,当有多个预订时,除非您查询的范围与现有预订重叠全部,否则您将获得匹配。您可以像这样重写它(请注意,当预留为空时,此查询也匹配):
{
"query": {
"bool": {
"must_not": {
"nested": {
"path": "reservations",
"query": {
"bool": {
"should": [
{
"range": {
"reservations.start_date": {
"gte": start_date,
"lt": end_date
}
}
},
{
"range": {
"reservations.end_date": {
"gte": start_date,
"lt": end_date
}
}
},
{
"bool": {
"must": [
{
"range": {
"reservations.start_date": {
"lt": start_date
}
}
},
{
"range": {
"reservations.end_date": {
"gt": end_date
}
}
}
]
}
}
]
}
}
}
}
}
}
}