Skip to main content

Python Client

连接测试

命令行方式测试连接性

~ python
Python 3.9.13 (main, May 24 2022, 21:28:31)
>>> from elasticsearch import Elasticsearch
>>> client = Elasticsearch(['https://router.nasuyun.com:9200'], http_auth=('应用用户名', '用户密码'))
>>> client.info()
{'name': 'xxx-xxx-xxx-xxx', 'cluster_name': 'free', 'cluster_uuid': 'xxxxxxx', 'version': {'number': '6.8.23', 'build_flavor': 'default', 'build_type': 'docker', 'build_hash': 'a6ca469', 'build_date': '2022-09-18T06:39:32.583Z', 'build_snapshot': False, 'lucene_version': '7.7.3', 'minimum_wire_compatibility_version': '5.6.0', 'minimum_index_compatibility_version': '5.0.0'}, 'tagline': 'You Know, for Search'}

创建索引文档

创建 index.py

index.py
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch(['https://router.nasuyun.com:9200'], http_auth=('应用用户名', '用户密码'))

doc = {
'author': 'author_name',
'text': 'Interesting content...',
'timestamp': datetime.now(),
}
res = es.index(index="test-index", id=1, body=doc)
print(res['result'])

执行

python index.py

获取索引文档

get.py
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch(['https://router.nasuyun.com:9200'], http_auth=('应用用户名', '用户密码'))

res = es.get(index="test-index", id=1)
print(res['_source'])

搜索文档

search.py
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch(['https://router.nasuyun.com:9200'], http_auth=('应用用户名', '用户密码'))

res = es.search(index="test-index")
print("Got %s Hits:" % res['hits'])

返回

Got {'total': 1, 'max_score': 1.0, 'hits': [{'_index': 'test-index', '_type': '_doc', '_id': '1', '_score': 1.0, '_source': {'author': 'author_name', 'text': 'Interesting content...', 'timestamp': '2023-02-11T20:37:03.494719'}}]} Hits: