当我尝试使用脚本从 Elasticsearch 字段中的数组中删除项目时出现错误

I have errors when I try to remove an item from Array in Elasticsearch field using script

我试图从我的 elasticsearch 数组字段中删除一个项目,但它给我这个错误:

ERROR => TransportError(400, 'illegal_argument_exception', '[D3e7NWc][127.0.0.1:9300][indices:data/write/update[s]]')

我只想从数组中删除此项

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "customers",
                "_type": "customer",
                "_id": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                "_score": 1,
                "_source": {
                    "uid": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                    "email": "georgehatouts@gmail.com",
                    "favorites": [
                        "AV8My20P8yrUSAV2Zp6C",
                        "AV8Mw5zq8yrUSAV2Zp6A"  <--- I WANT TO REMOVE THIS ITEM
                    ],
                    "history": [],
                    "settings": {},
                    "purchases": [],
                    "created": 1508083496773,
                    "updated": 1508083496773
                }
            }
        ]
    }
}

这是我的 python 代码:

def remove_fav_product(uid, product_id):
    ''' Remove favorite product from customer favorites '''

    print('Start removing favorite product')
    print('UID => ', uid)
    print('product_id => ', product_id)

    # 1st check if the user has this product on favorites,
    # 2nd if the user doesn't have this remove it from the list

    timestamp = int(round(time.time() * 1000))

    doc = {
        "script" : {
            "inline":"ctx._source.favorites.remove(params.product_id)",
            "params":{
                "product_id":product_id
            }
        }
    }

    es.update(index="customers", doc_type='customer', id=uid, body=doc)
    es.indices.refresh(index="customers")
    return jsonify({'message': 'customer_remove_fav_product'}), 200
#end

但是当我尝试在数组中添加新项目时是可行的

def add_favevorite_product(uid, fav_product):
    ''' Add new favorite product '''

    print('Start new favorite product')
    product_id = fav_product['products']

    # 1st check if the user has this product on favorites,
    # 2nd if the user doesn't have this remove it from the list

    timestamp = int(round(time.time() * 1000))

    doc = {
        "script" : {
            "inline":"ctx._source.favorites.add(params.product_id)",
            "params":{
                "product_id":product_id
            }
        }
    }

    es.update(index="customers", doc_type='customer', id=uid, body=doc)
    es.indices.refresh(index="customers")
    return jsonify({'message': 'customer_updated'}), 200
#end

然而,当我尝试在我的 elasticsearch.yml 中添加 script.inline: onscript.indexed: on 但我不确定这是否可以,请查看底部的最后两行,是这么好?

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
#network.host: 127.0.0.1
#
# Set a custom port for HTTP:
#
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes: 3
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true

#script.inline: on
#script.indexed: on

试试这个。将此命令嵌入到您的代码中,看看是否可行。

POST test/array/1/_update
{
  "script": {
    "inline": "for(int i=0;i<ctx._source.favorites.size();i++){if(ctx._source.favorites[i]==params.product_id){ctx._source.favorites.remove(i)}}",
    "params": {
      "product_id": 1
    }
  }
}

感谢 Hatim Stovewala 我只是添加了这段代码

doc = {
        "script" : {
            "inline": "for(int i=0;i<ctx._source.favorites.size();i++){if(ctx._source.favorites[i]==params.product_id){ctx._source.favorites.remove(i)}}",
            "lang": "painless",
            "params":{
                "product_id":product_id
            }
        }
    }

对于您的示例,从列表中删除与特定值匹配的元素的最简单方法是使用 "removeIf" 方法。下面的代码将删除与 params 下的字符串匹配的产品 ID。

POST test/array/1/_update

{"script":{"lang":"painless","source":"ctx._source.favorites.removeIf(e -> e.equals(params.product_id))","params":{"product_id":"AV8Mw5zq8yrUSAV2Zp6A"}}}