Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

elasticsearch python

作者:古枕清风   发布日期:2025-07-07   浏览:86

# 导入Elasticsearch库
from elasticsearch import Elasticsearch

# 创建Elasticsearch客户端实例
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

# 定义索引名称和文档类型
index_name = 'my_index'
doc_type = 'my_type'

# 插入文档示例
doc = {
    'author': 'John Doe',
    'text': 'Elasticsearch is a powerful search engine.'
}
res = es.index(index=index_name, doc_type=doc_type, id=1, body=doc)
print('插入结果:', res['result'])

# 查询文档示例
res = es.get(index=index_name, doc_type=doc_type, id=1)
print('查询结果:', res['_source'])

# 搜索文档示例
search_param = {
    'query': {
        'match': {
            'text': 'powerful'
        }
    }
}
res = es.search(index=index_name, doc_type=doc_type, body=search_param)
print('搜索结果:', res['hits']['hits'])

解释说明:

  1. 导入Elasticsearch库:首先需要安装并导入elasticsearch库,可以通过pip install elasticsearch来安装。
  2. 创建Elasticsearch客户端实例:通过指定主机和端口来连接到Elasticsearch集群。
  3. 定义索引名称和文档类型:在Elasticsearch中,数据存储在索引中,每个文档都有一个类型(虽然在7.x版本之后,文档类型的概念已经逐渐被弱化)。
  4. 插入文档:使用index方法向指定的索引中插入一条文档,并打印插入结果。
  5. 查询文档:使用get方法根据ID获取指定文档,并打印查询结果。
  6. 搜索文档:使用search方法根据查询条件搜索文档,并打印搜索结果。

上一篇:python中if

下一篇:python文件读取

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站