【问题标题】:Elasticsearch - Return only part of an arrayElasticsearch - 仅返回数组的一部分
【发布时间】:2017-11-08 21:35:04
【问题描述】:

我有以下文件

    {
      "id": 1,
      "store": "xyz",
      "products": [
        {
          "object": {
            "name": "chair",
            "code": "2584"
          },
          "parts": [
            {
              "material": "wood"
            },
            {
              "material": "steel"
            }
          ]
        }
      ]
    },
    {
      "id": 2,
      "store": "abc",
      "products": [
        {
          "object": {
            "name": "chair",
            "code": "2584"
          },
          "parts": [
            {
              "material": "wood"
            },
            {
              "material": "steel"
            }
          ]
        },
        {
          "object": {
            "name": "table",
            "code": "2678"
          },
          "parts": [
            {
              "material": "wood"
            },
            {
              "material": "steel"
            }
          ]
        }
      ]
    }

所以它是这样的:商店列表 -> 产品列表 -> 零件列表

现在我想查询所有在产品列表中有椅子的商店,但我不想在响应中包含所有产品

例如,商店“abc”应该为查询返回:

{
 "id": 2,
 "store": "abc",
 "products": [
   {
     "object": {
       "name": "chair",
       "code": "2584"
     },
     "parts": [
       {
         "material": "wood"
       },
       {
         "material": "steel"
       }
     ]
   }
}

目前我的映射是:

"products.object": {
  "type": "object",
  "properties": {
    "code": {
      "type": "text",
      "fielddata": true
    },
    "name": {
      "type": "text",
      "fielddata": true
    }
  }
},
"products.parts": {
  "store": false,
  "type": "long",
  "index": false
},

我应该使用什么类型的查询以及应该如何进行映射?

提前谢谢你

编辑:

补充一下我的问题,我的目标是删除所有与 hits 数组中的查询不匹配的产品

所以响应应该包含 id、变量“store”等等。但不是与名称“椅子”不匹配的产品(以呼应我的示例)

【问题讨论】:

    标签: elasticsearch elasticsearch-5


    【解决方案1】:

    您可以将查询与术语聚合一起使用:

    {
      "size": 0,
      "query": {
        "bool": {
          "must": {
            "products.object.name": "chair"
          }
        }
      },
      "aggs": {
        "stores_aggregation": {
          "terms": {
            "field": "store"
          }
        }
      }
    }
    

    --> size:0 决定不返回任何文件。

    --> 查询将仅按椅子过滤

    --> 聚合将为您提供包含所有相关商店的存储桶列表,请查看 here 了解更多信息。

    另外一件事,我建议你去嵌套Nested Datatype,看我的回答here 了解好处。

    【讨论】:

    • 嗨,我已经尝试过您的解决方案并且它有效,但我的问题似乎不够精确,我正在更新我的问题以提供更多信息
    • 在我之前的评论中添加更多内容:您的解决方案意味着我不能只在聚合中获取“存储”字段。但我想保留我的文档的所有信息,除了我没有搜索的产品,即:从命中内的数组中删除产品
    • 确实可以使用嵌套类型。我将尝试添加一些示例。我的回答here也可以帮助你理解这个概念。
    猜你喜欢
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2015-11-22
    • 2014-01-20
    • 2013-01-22
    相关资源
    最近更新 更多