当我尝试使用脚本从Elasticsearch字段中的Array中删除项时,我有错误

问题描述 投票:1回答:2

我正在尝试从弹性搜索数组字段中删除一个项目,但它给了我这个错误:

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": "[email protected]",
                    "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
python elasticsearch elasticsearch-5
2个回答
3
投票

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

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
    }
  }
}

0
投票

Thnx to 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
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.