【问题标题】:Compare data between MongoDB and MySQL using python script使用 python 脚本比较 MongoDB 和 MySQL 之间的数据
【发布时间】:2021-04-15 03:29:10
【问题描述】:

我正在开发一个使用 MySQL 和 MongoDB 来存储其数据的 Django 应用程序。我需要做的是比较存储在 MongoDB 的集合中和存储在 MySQL 的表中的数据。

例如,我的 MySQL 数据库包含表“relation”,它是使用以下方法创建的:

CREATE TABLE relations (service_id int, beneficiary_id int, PRIMARY KEY (service_id, beneficiary_id));

我的 MongoDB 包含一个名为“relation”的集合,它预计会存储与 MySQL 中的关系表相同的数据。以下是集合“关系”的一个文档:

{'_id': 0, 'service_id': 1, 'beneficiary_id': 32}

我尝试创建一个 python 脚本来比较 MySQL 中的关系表和 Mongo 中的关系集合之间的数据。该脚本的工作原理如下:

mysql_relations = Relations.objects.values('beneficiary_id', 'service_id')
mongo_relations_not_in_mysql = relations_mongodb.find({'$nor':list(mysql_relations)})

mongo_relations = relations_mongodb.find({}, {'_id': 0, 'beneficiary_id':1, 'service_id': 1})
filter_list = Q()
for mongo_relation in mongo_relations:
    filter_list &= Q(mongo_relation)
mysql_relations_not_in_mongo = Relations.objects.exclude(filter_list)

但是,此代码需要很长时间。 我认为主要问题是因为主键由 2 列组成,这需要使用 Q() 和 '$nor'。

你有什么建议?

【问题讨论】:

    标签: python mysql mongodb pymongo pymysql


    【解决方案1】:

    以防万一有人感兴趣,我使用了以下解决方案来优化数据比较。

    (想法是创建一个临时的 MySQL 表来存储 mongo 的数据,然后在 MySQL 表之间进行比较)。代码如下:

    1. 从 MongoDB 获取关系

      mongo_relations = relations_mongodb.find({}, {'_id': 0, 'service_id': 1, 'beneficiary_id': 1})
      
    2. 创建一个临时的 MySQL 表来存储 MongoDB 的关系

      cursor = connection.cursor()
      cursor.execute(
          "CREATE TEMPORARY TABLE temp_relations (service_id int, beneficiary_id int, INDEX `id_related` (`service_id`, `beneficiary_id`) );"
      )
      
    3. 插入 MongoDB 的关系而不是刚刚创建的临时表

      cursor.executemany(
          'INSERT INTO temp_relations (service_id, beneficiary_id) values (%(service_id)s, %(beneficiary_id)s) ',
              list(mongo_relations)
      )
      
    4. 获取MySQL中不存在的MongoDB关系

      cursor.execute(
          "SELECT service_id, beneficiary_id FROM temp_relations WHERE (service_id, beneficiary_id) NOT IN ("
              "SELECT service_id, beneficiary_id FROM relations);"
      )
      mongo_relations_not_in_mysql = cursor.fetchall()
      
    5. 获取MongoDB中不存在的MySQL关系

      cursor.execute(
          "SELECT id, service_id, beneficiary_id, date FROM relations WHERE (service_id, beneficiary_id) not IN ("
              "SELECT service_id, beneficiary_id FROM temp_relations);"
      )
      mysql_relations_not_in_mongo = cursor.fetchall()
      cursor.close()   # Close the connection to MySQL
      

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多