【问题标题】:Elasticsearch Node.js client: delete a nested element from a objectElasticsearch Node.js 客户端:从对象中删除嵌套元素
【发布时间】:2021-09-28 10:25:13
【问题描述】:

我有一个像下面这样的对象

 "_source": {
                "name": "capsicum",
                "id": "60f759b934e43100195c6142",
                "userId": "60f7209ecdb2c0001935fa8f",
                "version": 1,
                "tags": [
                    {
                        "name": "fruit",
                        "id": "60f75990be3b530019062790",
                        "group": "location"
                    },
                    {
                        "name": "green",
                        "id": "60f75990be3b530019062766",
                        "group": "food"
                    },
                    {
                        "name": "red",
                        "id": "60f75990be3b530019062722",
                        "group": "food"
                    },
                    {
                        "name": "vegetable",
                        "id": "60f75990be3b53001906272d",
                        "group": "food"
                    }
                ]
            }

如何从标签中删除一个元素,在标签中添加一个元素,在单独的 api 调用中。 我尝试了以下代码来删除但不工作

elasticClient.updateByQuery(
        {
          index: ElasticIndexs.Products,
          body: {
            script: {
              source: `ctx._source.tags.removeIf(a -> a.id == params.id)`,
              params: {
                id: product.tag.id,
              },
            },
            query: {
              match: {
                id: product.id,
              },
            },
          },
        },
        function (error, response) {
          console.log(response);
        }
      );

【问题讨论】:

  • 您从日志中得到什么错误?我相信您是从某个地方获取“product.id”和“product.tag.id”到此函数的,您能否确认在此处访问这些参数时没有未定义?
  • @HemedAli,感谢您的及时回复,但问题出在其他地方,如果您有兴趣查看答案,可以在 ans 部分找到。

标签: node.js elasticsearch


【解决方案1】:

添加:

  await elasticWrapper.client.update({
        index: ElasticIndexs.Products,
        id: data.id,
        body: {
          script: {
            inline: 'ctx._source.tags.add(params.tag)',
            // lang: 'painless',
            params: {
              tag: data.tag,
            },
          },
        },
      });

删除:

 await elasticWrapper.client.update({
        index: ElasticIndexs.Products,
        id: data.id,
        body: {
          script: {
            inline: `for (int i = 0; i < ctx._source.tags.size();
            i++){if(ctx._source.tags[i].id == params.id){ctx._source.tags.remove(i);}}`,
            params: {
              id: data.tag.id,
            },
          },
        },
      });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2020-11-21
    • 1970-01-01
    • 2022-07-19
    相关资源
    最近更新 更多