首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >弹性搜索中两种查询结果的差异

弹性搜索中两种查询结果的差异
EN

Stack Overflow用户
提问于 2018-04-11 13:20:42
回答 1查看 1.5K关注 0票数 0

假设我们有电子商务商店数据的索引,我们想要得到两个商店的产品列表的差异。

关于索引内容的信息:存储在每个文档中的示例数据如下所示:

代码语言:javascript
复制
{
   "product_name": "sample 1",
   "store_slug": "store 1",
   "sales_count": 42,
   "date": "2018-04-04"
}

以下是查询,让我所有的产品分别出现在2家商店,

代码语言:javascript
复制
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”。

EN

回答 1

Stack Overflow用户

发布于 2018-04-11 13:23:54

为什么不在一个查询中执行呢?

在商店1但不在商店2的产品:

代码语言:javascript
复制
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聚合,首先按产品,然后按存储,只选择只有一个存储桶的产品(使用管道聚合)。

代码语言:javascript
复制
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"
            }
          }
        }
      }
    }
  }
}'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49776252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档