Elasticsearch(ES):一种强大的中间件用于搜索和分析
Elasticsearch 是一个基于 Apache Lucene 的开源搜索和分析引擎。它设计用于云计算中,能够达到实时搜索,高可用,和大规模可伸缩。
以下是一些常见的 Elasticsearch 用法:
- 创建索引
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
doc = {
'name': 'John Doe',
'age': 30,
'about': 'I love to go rock climbing'
}
response = es.index(index=index_name, id=1, document=doc)
print(response['result'])
- 获取文档
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
response = es.get(index=index_name, id=1)
print(response['_source'])
- 更新文档
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
doc_id = 1
doc = {
'name': 'Jane Doe',
'age': 35,
'about': 'I love to collect rock albums'
}
response = es.update(index=index_name, id=doc_id, document=doc)
print(response['result'])
- 删除索引
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
response = es.delete(index=index_name)
print(response)
- 搜索文档
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
search_body = {
'query': {
'match': {
'about': 'rock'
}
}
}
response = es.search(index=index_name, body=search_body)
print(response['hits']['hits'])
- 使用聚合分析
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'test-index'
search_body = {
'size': 0,
'aggs': {
'group_by_age': {
'terms': {
'field': 'age'
}
}
}
}
response = es.search(index=index_name, body=search_body)
print(response['aggregations']['group_by_age']['buckets'])
注意:以上代码示例需要先安装 elasticsearch Python 客户端库,可以使用 pip install elasticsearch 命令进行安装。
以上就是 Elasticsearch 的一些基本用法,具体应用可能需要根据实际需求进行调整和扩展。
评论已关闭