python读写elasticsearch

目录

安装es客户端

插入数据

查找数据

插入2条数据

搜索数据

搜索全部数据

字段值搜索

浏览器查看索引

修改数据

立刻刷新数据

查数据量

查看索引是否存在

删除索引

新建索引

获取索引名称

curl转requests

计算IP

查向量数量

参考


安装es客户端

pip install elasticsearch==8.6

插入数据

from elasticsearch import Elasticsearch

es = Elasticsearch('http://es机器ip:9200')
print(es)

e1 = {'name': 'maomao','age':4,'color':'grey'}
res = es.index(index='love', document = e1)
print(res)
<Elasticsearch(['http://xx:9200'])>
{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}

查找数据

from elasticsearch import Elasticsearch

es = Elasticsearch('http://es机器ip:9200')
print(es)

res = es.get(index='love',id='WvtURIkBNiG-_5JL_iRN')
print(res)
print(res['_source'])
<Elasticsearch(['http://xx:9200'])>
{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_version': 1, '_seq_no': 0, '_primary_term': 1, 'found': True, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'name': 'maomao', 'age': 4, 'color': 'grey'}

插入2条数据

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

e1 = {'name': 'maomao','age':5,'color':'grey'}
e2 = {'name': 'benben','age':9,'color':'yellow'}
res1 = es.index(index='love', document = e1)
print(res1)
res2 = es.index(index='love', document = e2)
print(res2)
{'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 1, '_primary_term': 1}
{'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 2, '_primary_term': 1}

搜索数据

搜索全部数据
from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

res = es.search(index='love', query={'match_all':{}})
print(res)
print(res['hits'])
print(res['hits']['hits'])

print('\n------------------------')
for terms in res['hits']['hits']:
    print(terms)
{'took': 1, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 3, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}, {'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}]}}
{'total': {'value': 3, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}, {'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}]}
[{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}, {'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}]

------------------------
{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
{'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
字段值搜索
from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

res = es.search(index='love', query={'match':{'color':'grey'}})
print(res)
print(res['hits'])
print(res['hits']['hits'])

print('\n------------------------')
for terms in res['hits']['hits']:
    print(terms)
{'took': 6, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 0.4700036, 'hits': [{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}]}}
{'total': {'value': 2, 'relation': 'eq'}, 'max_score': 0.4700036, 'hits': [{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}]}
[{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}, {'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}]

------------------------
{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 0.4700036, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
浏览器查看索引

修改数据

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

es.index(index='love',id='XPtcRIkBNiG-_5JLmCSw',document={'name':'big-maomao'})

res = es.search(index='love', query={'match_all':{}})
for terms in res['hits']['hits']:
    print(terms)
{'_index': 'love', '_id': 'WvtURIkBNiG-_5JL_iRN', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'XftcRIkBNiG-_5JLmCTD', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'XPtcRIkBNiG-_5JLmCSw', '_score': 1.0, '_source': {'name': 'big-maomao'}}

立刻刷新数据

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

res = es.search(index='love', query={'match_all':{}})
for terms in res['hits']['hits']:
    print(terms)

es.delete(index='love',id='XvtMRYkBNiG-_5JLzSQ1')

es.indices.refresh(index='love')

print('\n-----------')
res = es.search(index='love', query={'match_all':{}})
for terms in res['hits']['hits']:
    print(terms)
{'_index': 'love', '_id': 'XvtMRYkBNiG-_5JLzSQ1', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
{'_index': 'love', '_id': 'X_tMRYkBNiG-_5JLzSRa', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YPtPRYkBNiG-_5JLSSTh', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
{'_index': 'love', '_id': 'YftPRYkBNiG-_5JLSST8', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YvtQRYkBNiG-_5JLBySH', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'Y_tQRYkBNiG-_5JLSyST', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}

-----------
{'_index': 'love', '_id': 'X_tMRYkBNiG-_5JLzSRa', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YPtPRYkBNiG-_5JLSSTh', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
{'_index': 'love', '_id': 'YftPRYkBNiG-_5JLSST8', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YvtQRYkBNiG-_5JLBySH', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'Y_tQRYkBNiG-_5JLSyST', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}

查数据量

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

res = es.search(index='love',query={'match_all': {}})
for i in res['hits']['hits']:
    print(i)

print('\n-----')
print(es.count()['count'])
{'_index': 'love', '_id': 'X_tMRYkBNiG-_5JLzSRa', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YPtPRYkBNiG-_5JLSSTh', '_score': 1.0, '_source': {'name': 'maomao', 'age': 5, 'color': 'grey'}}
{'_index': 'love', '_id': 'YftPRYkBNiG-_5JLSST8', '_score': 1.0, '_source': {'name': 'benben', 'age': 9, 'color': 'yellow'}}
{'_index': 'love', '_id': 'YvtQRYkBNiG-_5JLBySH', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}
{'_index': 'love', '_id': 'Y_tQRYkBNiG-_5JLSyST', '_score': 1.0, '_source': {'name': 'maomao', 'age': 4, 'color': 'grey'}}

-----
5

查看索引是否存在

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

print(es.indices.exists(index='h'))
print(es.indices.exists(index='love'))
False
True

删除索引

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xxx:9200')

if es.indices.exists(index='love'):
    es.indices.delete(index='love')
    print('delete index=love')

print(es.search(index='love', query={'match_all':{}}))

新建索引

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')

if es.indices.exists(index='love'):
    es.indices.delete(index='love')
    print('delete index=love')

if not es.indices.exists(index='love'):
    es.indices.create(index='love')
    print('create index=love')

res = es.search(index='love', query={'match_all':{}})
print(res)
print(res['hits']['hits'])

es.index(index='love', document={'hello': '000'})
es.indices.refresh()

print('\n---------')
res = es.search(index='love', query={'match_all': {}})
print(res['hits']['hits'])
delete index=love
create index=love
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 0, 'relation': 'eq'}, 'max_score': None, 'hits': []}}
[]

---------
[{'_index': 'love', '_id': 'aPuNRYkBNiG-_5JL_iT6', '_score': 1.0, '_source': {'hello': '000'}}]

获取索引名称

from elasticsearch import Elasticsearch

es = Elasticsearch('http://xx:9200')
res = es.indices.get(index='*')
print(res.keys())
dict_keys(['image-index', 'love'])

curl转requests

计算IP
import requests

headers = {'Content-Type': 'application/json'}
json_data = {"knn": {
                "field": "vector",
                "query_vector": [0.1,0.98995,0.1],
                "k": 1,
                "num_candidates": 100
            }}

res = requests.post('http://xx:9200/test03/_search?pretty',
                    headers=headers,json=json_data)
print(res.json())
{'took': 1, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 1, 'relation': 'eq'}, 'max_score': 0.60399497, 'hits': [{'_index': 'test03', '_id': 'h_v5TYkBNiG-_5JLvCS6', '_score': 0.60399497, '_source': {'vector': [0.1, 0.1, 0.98995]}}]}}
查向量数量
import requests

# curl -X GET "localhost:9200/_cat/count/my-index-000001?v=true&pretty"
res = requests.get('http://xx:9200/_cat/count/test03')
print(res.text.strip().split(' ')[-1])
参考
  • https://blog.csdn.net/weixin_39723544/article/details/109237175

  • https://www.elastic.co/guide/en/elasticsearch/reference/8.6/indices-create-index.html

  • https://blog.csdn.net/qq_37754830/article/details/126856337

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
利用Python操作Elasticsearch可以使用elasticsearchelasticsearch-dsl这两个库,也可以使用更为简单的es-pandas库。其中,elasticsearch库提供了与Elasticsearch交互的低级接口,而elasticsearch-dsl库则提供了更高级别的查询构建器和对象映射器。es-pandas库则提供了一种将Elasticsearch数据转换为pandas DataFrame的简单方法。 以下是一个使用elasticsearch库进行查询的例子: ```python from elasticsearch import Elasticsearch # 连接到Elasticsearch es = Elasticsearch() # 查询所有文档 res = es.search(index="my_index", body={"query": {"match_all": {}}}) # 输出结果 for hit in res['hits']['hits']: print(hit['_source']) ``` 以下是一个使用elasticsearch-dsl库进行查询的例子: ```python from elasticsearch import Elasticsearch from elasticsearch_dsl import Search # 连接到Elasticsearch es = Elasticsearch() # 创建查询对象 s = Search(using=es, index="my_index").query("match", title="python") # 执行查询并输出结果 response = s.execute() for hit in response: print(hit.title) ``` 以下是一个使用es-pandas库将Elasticsearch数据转换为pandas DataFrame的例子: ```python from es_pandas import es_pandas # 将Elasticsearch数据转换为pandas DataFrame df = es_pandas.DataFrame({ "host": {"field": "host.keyword"}, "response": {"field": "response_time_ms"}, "timestamp": {"field": "@timestamp", "dtype": "datetime64[ns]"} }, es_url="http://localhost:9200", es_index_pattern="my_index-*") # 输出DataFrame print(df.head()) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值