Python中MongoDB和Elasticsearch的集成方法

2023-04-15 00:00:00 python 方法 集成

Python中MongoDB和Elasticsearch可以通过elasticsearch-py库实现集成。下面是详细的集成方法:

  1. 安装elasticsearch-py库
pip install elasticsearch
  1. 连接MongoDB
import pymongo

client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['test_database']
collection = db['test_collection']
  1. 连接Elasticsearch
from elasticsearch import Elasticsearch

es = Elasticsearch()
  1. 将MongoDB中的数据放入Elasticsearch中
for item in collection.find():
    es.index(index='my_index', doc_type='my_type', id=str(item['_id']), body=item)
  1. 搜索数据
res = es.search(index='my_index', body={"query": {"match": {"content": "pidancode.com"}}})
for hit in res['hits']['hits']:
    print(hit['_source'])

完整代码如下:

import pymongo
from elasticsearch import Elasticsearch

# 连接MongoDB
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['test_database']
collection = db['test_collection']

# 连接Elasticsearch
es = Elasticsearch()

# 将MongoDB中的数据放入Elasticsearch中
for item in collection.find():
    es.index(index='my_index', doc_type='my_type', id=str(item['_id']), body=item)

# 搜索数据
res = es.search(index='my_index', body={"query": {"match": {"content": "pidancode.com"}}})
for hit in res['hits']['hits']:
    print(hit['_source'])

相关文章