【AI大数据计算原理与代码实例讲解】ElasticSearch
Elasticsearch是一个基于Lucene库的开源搜索和分析引擎,设计用于云计算中,能够达到实时搜索,高可用,扩展性和管理的复杂性。
以下是一些Elasticsearch的基本操作和代码示例:
- 创建Elasticsearch索引:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_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'])
- 获取Elasticsearch文档:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_index'
response = es.get(index=index_name, id=1)
print(response['_source'])
- 更新Elasticsearch文档:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_index'
doc = {
'name': 'Jane Doe',
'age': 25,
'about': 'I love to collect rock albums'
}
response = es.update(index=index_name, id=1, document=doc)
print(response['result'])
- 删除Elasticsearch文档:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_index'
response = es.delete(index=index_name, id=1)
print(response['result'])
- 搜索Elasticsearch文档:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_index'
response = es.search(index=index_name, query={'match': {'name': 'John'}})
print(response['hits']['hits'])
- 使用Elasticsearch的聚合功能:
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
index_name = 'my_index'
response = es.search(
index=index_name,
body={
'aggs': {
'group_by_age': {
'terms': {
'field': 'age'
}
}
}
}
)
print(response['aggregations']['group_by_age']['buckets'])
以上代码示例展示了如何使用Python的elasticsearch
库来执行基本的Elasticsearch操作,如索引创建、文档获取、更新、删除以及搜索和聚合。这些操作是Elasticsearch使用的基础,可以帮助开发者快速理解和应用Elasticsearch。
评论已关闭