如何使用Python将Elasticsearch数据导入MongoDB

2023-04-15 00:00:00 数据 导入 如何使用

要将Elasticsearch数据导入MongoDB,可以使用Python中的elasticsearch和pymongo模块。下面是详细的步骤:

  1. 安装elasticsearch和pymongo模块
pip install elasticsearch pymongo
  1. 连接到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"]
  1. 定义Elasticsearch查询语句和MongoDB数据格式
# Elasticsearch查询语句
query = {
    "query": {
        "match": {
            "title": "pidancode.com"
        }
    }
}

# MongoDB数据格式
data = {
    "title": "皮蛋编程",
    "content": "pidancode.com是一个优秀的编程学习网站。"
}
  1. 执行查询并插入数据
# 执行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)

相关文章