我在python中使用elasticsearch。并在python中使用dsl
驱动程序。在
我的剧本如下。在
import time
from elasticsearch_dsl import DocType, String
from elasticsearch import exceptions as es_exceptions
from elasticsearch_dsl.connections import connections
ELASTICSEARCH_INDEX = 'test'
class StudentDoc(DocType):
student_id = String(required=True)
tags = String(null_value=[])
class Meta:
index = ELASTICSEARCH_INDEX
def save(self, **kwargs):
'''
Override to set metadata id
'''
self.meta.id = self.student_id
return super(StudentDoc, self).save(**kwargs)
# Define a default Elasticsearch client
connections.create_connection(hosts=['localhost:9200'])
# create the mappings in elasticsearch
StudentDoc.init()
student_doc_obj = \
StudentDoc(
student_id=str(1),
tags=['test'])
try:
student_doc_obj.save()
except es_exceptions.SerializationError as ex:
# catch both exception raise by elasticsearch
LOGGER.error('Error while creating elasticsearch data')
LOGGER.exception(ex)
else:
print "*"*80
print "Student Created:", student_doc_obj
print "*"*80
search_docs = \
StudentDoc \
.search().query('ids',
values=["1"])
try:
student_docs = search_docs.execute()
except es_exceptions.NotFoundError as ex:
LOGGER.error('Unable to get data from elasticsearch')
LOGGER.exception(ex)
else:
print "$"*80
print student_docs
print "$"*80
time.sleep(2)
search_docs = \
StudentDoc \
.search().query('ids',
values=["1"])
try:
student_docs = search_docs.execute()
except es_exceptions.NotFoundError as ex:
LOGGER.error('Unable to get data from elasticsearch')
LOGGER.exception(ex)
else:
print "$"*80
print student_docs
print "$"*80
在这个脚本中,我正在创建StudentDoc
,并在创建时尝试访问同一个文档。我得到empty
响应时,做search
记录。在
输出
^{pr2}$save
命令执行并存储数据,那么为什么search
不返回tat数据。在2
第二次睡眠后,它返回数据。:(
尝试使用curl
命令执行相同的操作,输出相同。在
echo "Create Data"
curl http://localhost:9200/test/student_doc/2 -X PUT -d '{"student_id": "2", "tags": ["test"]}' -H 'Content-type: application/json'
echo
echo "Search ID"
curl http://localhost:9200/test/student_doc/_search -X POST -d '{"query": {"ids": {"values": ["2"]}}}' -H 'Content-type: application/json'
echo
在弹性搜索中存储数据有延迟吗?在
是的,为新文档编制索引后,在刷新索引之前,该文档将不可用。不过,你有几个选择,主要的是。在
A.您可以在保存
student_doc_obj
之后并在搜索之前使用基础连接refresh
索引test
:B.您可以
^{pr2}$get
而不是搜索它,因为get
是完全实时的,不需要等待刷新:类似地,使用curl,您只需在PUT调用中添加
refresh
查询字符串参数或者您可以简单地通过id获取文档
相关问题 更多 >
编程相关推荐