gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:54:20 44 4
gpt4 key购买 nike

我想更新用户最喜欢的产品,但是我无法使用python来做到这一点。此示例与用户添加和删除标签相同

这是我对客户INDEX的架构

"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。我想将此文档更新为如下形式:
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "customers",
"_type": "customer",
"_id": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
"_score": 1,
"_source": {
"uid": "QOTzXMUcrnbsYyFKeouHnjlkjQB3",
"email": "george@gmail.com",

"favorites": ['product_id_1', 'product_id_2', 'product_id_3'], < ---- this is the problem

"history": ['id_1', 'id_2', 'id_3'],
"settings": {},
"purchases ": [],
"created": 1507892081201,
"updated": 1507892081201
}
}
]
}

我已经尝试过此代码,但是不起作用:
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
}
}
]
}

最佳答案

试试这个:

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")

关于python - 如何在Elasticsearch和Python中更新标签数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46728783/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com