更新elasticsearch中的索引时出现RequestError

Pan*_*arg 5 python elasticsearch

我有一个在弹性搜索中索引的记录,带有一定的时间戳.我试图使用以下代码更新记录(在python中):

from elasticsearch import Elasticsearch
from datetime import datetime
import pytz

es = Elasticsearch()
time = datetime.utcnow().replace(tzinfo=pytz.utc)
msg = {'_id': 1, 'text': 'Hello World'}
es.index(index='idx', doc_type='dtype', id=msg['_id'], body=msg, timestamp=time, ttl='30d')
msg['text'] = 'New Message'
es.update(index='idx', doc_type='dtype', id=msg['_id'], body=msg, timestamp=time, ttl='30d')  
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

RequestError: TransportError(400, u'ActionRequestValidationException[Validation Failed: 1: script or doc is missing;]')
Run Code Online (Sandbox Code Playgroud)

可能是什么原因呢?

Hes*_*oon 14

消息号400表示您有"错误请求".请求正文/ URL不是预期的.

在这种情况下,这是因为您不在身体中使用脚本或doc.有关更多信息,请查看Update API文档.

以下代码解决了您的问题:

from elasticsearch import Elasticsearch
from datetime import datetime
import pytz

es = Elasticsearch()
time = datetime.utcnow().replace(tzinfo=pytz.utc)
msg = {'_id': 1, 'text': 'Hello World'}
es.index(index='idx', doc_type='dtype', id=msg['_id'], body=msg, timestamp=time, ttl='30d')
msg2 = '''{"doc": {"text": "New Message"}}'''
es.update(index='idx', doc_type='dtype', id=msg['_id'], body=msg2, timestamp=time, ttl='30d')
Run Code Online (Sandbox Code Playgroud)

通过围绕要通过doc标记更改的信息,您可以告诉ElasticSearch您要将值替换为部分文档的值.