如何在Elasticsearch和Python中更新标签数组列表

2024-10-03 15:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更新用户最喜欢的产品,我不能用python来更新,有任何解决方案。此示例与用户添加和删除标记相同

这是我在客户索引上的模式

"hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "customers",
                "_type": "customer",
                "_id": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                "_score": 1,
                "_source": {
                    "uid": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                    "email": "george@gmail.com",
                    "favorites": [],  < ---- this is the problem
                    "history": [],
                    "settings": {},
                    "purchases ": [],
                    "created": 1507892081201,
                    "updated": 1507892081201
                }
            }
        ]
    }

如您所见,我希望数组收藏夹存储用户选择为收藏夹产品的产品ID。我想把这个文件更新成这样:

^{pr2}$

我尝试过此代码,但不起作用:

fav_product = {
   "user_id": "user_1",
   "product_id": "favorite_product_1",
}

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

    user_id = fav_product['user_id']
    product_id = fav_product['product_id']

    print('Start new favorite product')

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

    doc = {
        'favorites' : "ctx._source.tags.add(product_id)",
        'created': timestamp,
        'updated': timestamp
    }


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

从服务器获得此响应:

"hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "customers",
                "_type": "customer",
                "_id": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                "_score": 1,
                "_source": {
                    "uid": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
                    "email": "george@gmail.com",
                    "favorites": "ctx._source.favorites.add(AV8PsBG_oWUfB334-p5b)",
                    "history": [],
                    "settings": {},
                    "purchases ": [],
                    "created": 1507893703655,
                    "updated": 1507893703655
                }
            }
        ]
    }

Tags: idsourceindexdoc产品customerproductscore
1条回答
网友
1楼 · 发布于 2024-10-03 15:21:27

试试这个:

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

user_id = fav_product['user_id']
product_id = fav_product['product_id']

print('Start new favorite product')


doc = {
    "script" : {
        "inline":"ctx._source.favorites.add(params.product_id)",
        "params":{
            "product_id":product_id
        }
    }
}
es.update(index="customers", doc_type='customers', id= user_id, body=doc)
es.indices.refresh(index="test")

相关问题 更多 >