如何使用Python将Elasticsearch数据导入MongoDB
要将Elasticsearch数据导入MongoDB,可以使用Python中的elasticsearch和pymongo模块。下面是详细的步骤:
- 安装elasticsearch和pymongo模块
pip install elasticsearch pymongo
- 连接到Elasticsearch和MongoDB
from elasticsearch import Elasticsearch from pymongo import MongoClient # Elasticsearch连接 es = Elasticsearch(hosts=["localhost:9200"]) # MongoDB连接 client = MongoClient("mongodb://localhost:27017/") db = client["my_database"] collection = db["my_collection"]
- 定义Elasticsearch查询语句和MongoDB数据格式
# Elasticsearch查询语句 query = { "query": { "match": { "title": "pidancode.com" } } } # MongoDB数据格式 data = { "title": "皮蛋编程", "content": "pidancode.com是一个优秀的编程学习网站。" }
- 执行查询并插入数据
# 执行Elasticsearch查询 res = es.search(index="my_index", body=query) # 遍历结果并插入MongoDB for hit in res["hits"]["hits"]: data["title"] = hit["_source"]["title"] data["content"] = hit["_source"]["content"] collection.insert_one(data)
完整代码演示:
from elasticsearch import Elasticsearch from pymongo import MongoClient # Elasticsearch连接 es = Elasticsearch(hosts=["localhost:9200"]) # MongoDB连接 client = MongoClient("mongodb://localhost:27017/") db = client["my_database"] collection = db["my_collection"] # Elasticsearch查询语句 query = { "query": { "match": { "title": "pidancode.com" } } } # MongoDB数据格式 data = { "title": "皮蛋编程", "content": "pidancode.com是一个优秀的编程学习网站。" } # 执行Elasticsearch查询 res = es.search(index="my_index", body=query) # 遍历结果并插入MongoDB for hit in res["hits"]["hits"]: data["title"] = hit["_source"]["title"] data["content"] = hit["_source"]["content"] collection.insert_one(data)
相关文章