【问题标题】:Add and delete object in nested property ElasticSearch在嵌套属性 ElasticSearch 中添加和删除对象
【发布时间】:2020-06-05 09:11:04
【问题描述】:

如何在 ElasticSearch 的嵌套属性中删除和添加项目?大多数示例都不起作用。

【问题讨论】:

  • 他们怎么不工作了?你试过什么?请考虑通过一些示例扩展您的问题并增加清晰度。

标签: php elasticsearch elasticsearch-painless


【解决方案1】:

一种更简单的删除项目的方法(灵感来自my other answer here)。

没有 for 循环,没有 if :-)

$this->getClient()->update(
    [
        'index' => $this->getIndexName(),
        'id' => $Item->getReportId(),
        'body' => [
            'script' => [
                'lang' => 'painless',
                'inline' => 'ctx._source.reports.removeAll{ it -> it.entry_id == params.entry_id && it.source == params.source }',
                'params' => ['entry_id' => (string)$Item->getEntryId(), 'source' => $Item->getTableName()],
            ],
        ],
    ]
);

【讨论】:

    【解决方案2】:

    我花了很多时间来弄清楚如何将新对象添加到 ElasticSearch 的嵌套数组中以及如何删除它。 StackOverflow 上有很多答案,但大多数都已经过时了。于是就有了例子:

        $this->getClient()->update(
            [
                'index' => $this->getIndexName(),
                'id' => $Item->getReportId(),
                'body' => [
                    'script' => [
                        'lang' => 'painless',
                        'inline' => 'int idx = -1;
                         for (int i = 0; i < ctx._source.reports.length; ++i) {
                          if (ctx._source.reports[i].entry_id == params.entry_id && ctx._source.reports[i].source == params.source) { 
                           idx=i; 
                          } 
                         } 
                         if (idx != -1)
                          ctx._source.reports.remove(idx);',
                        'params' => ['entry_id' => (string)$Item->getEntryId(), 'source' => $Item->getTableName()],
                    ],
                ],
            ]
        );
    
        $this->getClient()->update(
            [
                'index' => $this->getIndexName(),
                'id' => $Item->getReportId(),
                'body' => [
                    'script' => [
                        'lang' => 'painless',
                        'inline' => 'ctx._source.reports.add(params.object)',
                        'params' => ['object' => $entry]
                    ],
                ],
            ]
        );
    

    【讨论】:

    • (string) 在这里转换,因为== 关心类型
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2013-11-07
    • 2018-12-22
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多