假设我们有电子商务商店数据的索引,我们想要得到两个商店的产品列表的差异。
关于索引内容的信息:存储在每个文档中的示例数据如下所示:
{
"product_name": "sample 1",
"store_slug": "store 1",
"sales_count": 42,
"date": "2018-04-04"
}以下是查询,让我所有的产品分别出现在2家商店,
Data for store 1
curl -XGET 'localhost:9200/store/_search?pretty' -H 'Content-Type: application/json' -d'
{
"_source": ["product_name"],
"query": {
"constant_score" : {
"filter" : {
"bool" : {
"must" : [
{ "term" : { "store_slug" : "store_1"}}]}}}}}'
Data for store 2
curl -XGET 'localhost:9200/store/_search?pretty' -H 'Content-Type: application/json' -d'
{
"_source": ["product_name"],
"query": {
"constant_score" : {
"filter" : {
"bool" : {
"must" : [
{ "term" : { "store_slug" : "store_2"}}]}}}}}'elasticsearch查询是否有可能获得这两种结果的差异(而不使用某些脚本/其他语言)?
例如,上述操作:假设“商店1”销售产品“1",”商店2“和”商店2“销售产品”1“、”产品3",因此“商店1”和“商店2”的产品差异预期产出为“产品2”。
发布于 2018-04-11 13:23:54
为什么不在一个查询中执行呢?
在商店1但不在商店2的产品:
curl -XGET 'localhost:9200/store/_search?pretty' -H 'Content-Type: application/json' -d '{
"_source": [
"product_name"
],
"query": {
"constant_score": {
"filter": {
"bool": {
"filter": [
{
"term": {
"store_slug": "store_1"
}
}
],
"must_not": [
{
"term": {
"store_slug": "store_2"
}
}
]
}
}
}
}
}'你也可以轻易地做相反的事情。
更新
在阅读了更新之后,我认为解决这个问题的最好方法是使用terms聚合,首先按产品,然后按存储,只选择只有一个存储桶的产品(使用管道聚合)。
curl -XGET 'localhost:9200/store/_search?pretty' -H 'Content-Type: application/json' -d '{
{
"size": 0,
"aggs": {
"products": {
"terms": {
"field": "product_name"
},
"aggs": {
"stores": {
"terms": {
"field": "store_slug"
}
},
"min_bucket_selector": {
"bucket_selector": {
"buckets_path": {
"count": "stores._bucket_count"
},
"script": {
"source": "params.count == 1"
}
}
}
}
}
}
}'https://stackoverflow.com/questions/49776252
复制相似问题