mongo helper
import datetime
import pymongo
import click
# 数据库基本信息
db_configs = {
'type': 'mongo',
'host': '127.0.0.1',
'port': '27017',
"user": "",
"password": "",
'db_name': 'spider'
}
class Mongo():
def __init__(self):
self.db_name = db_configs.get("db_name")
self.host = db_configs.get("host")
self.port = db_configs.get("port")
self.client = pymongo.MongoClient(f'mongodb://{self.host}:{self.port}', connect=False, maxPoolSize=10)
self.username = db_configs.get("user")
self.password = db_configs.get("passwd")
if self.username and self.password:
self.db = self.client[self.db_name].authenticate(self.username, self.password)
self.db = self.client[self.db_name]
def reset_status(self, col="dianping_seed_data"):
item = dict()
item["status"] = 0
item["update_time"] = datetime.datetime.now()
self.db[col].update_many({'$or': [{'status': 1}, {'status': 3}]}, {'$set': item})
def reset_all_status(self, col="dianping_seed_data"):
item = dict()
item["status"] = 0
item["count"] = 0
item["update_time"] = datetime.datetime.now()
self.db[col].update_many({}, {'$set': item})
def add_index(self, col="dianping_seed_data"):
# status_code 0:初始,1:开始下载,2下载完了
self.db[col].create_index([('status', pymongo.ASCENDING)], unique=True)
def get_index(self, col="dianping_seed_data"):
index_list = self.db[col].list_indexes()
for index in index_list:
print(index)
# 找出重复的放入result表中
def find_duplicate(self, col="dianping_seed_data"):
"""
{'$out': 'result'}:聚合之后将结果写到新的集合result表里。
:param col:
:return:
"""
group = {'$group': {
'_id': {'url': "$url"}, # 以url分组
'_id_list': {'$addToSet': "$_id"}, # _id字段添加到返回结果里面去
'count': {'$sum': 1} # 结果计数加一
}}
# match将上面传过来的结果做进一步处理
match = {"$match": {"count": {"$gt": 1}}}
# 聚合之后的结果输出到表_duplicate_result
out = {'$out': f'{col.split("_")[0]}_duplicate_result'}
try:
result = self.db[col].aggregate([
group, match, out
], allowDiskUse=True)
print("聚合成功")
except Exception as e:
print("聚合失败", e.args)
return result
def delete_dup(self, col="dianping_seed_data"):
dup = f'{col.split("_")[0]}_duplicate_result'
delete_data = self.db[dup].find()
try:
for d in delete_data:
# 保留一条
unique_id_list = d.get("_id_list")[1:]
for did in unique_id_list:
self.db[col].delete_one({'_id': did})
print("准备删除表")
self.db[dup].drop()
print("删除表成功")
except Exception as e:
print("删除的时候出现问题", e.args)
@click.command()
@click.option('--s', type=str, help="状态:all表示全部重置为0,two:表示重置状态为1、3的重置为0")
@click.option('--i', type=str, help="a:增加索引 g:获取索引")
@click.option('--d', type=str, help="d:删除 f:查询并生成聚合之后的结果")
def run(s, i, d):
m = Mongo()
if s:
print("获取参数为:", s)
if s == "all":
print("所有数据状态重置为0:", s)
m.reset_all_status()
elif s == "two":
m.reset_status()
print("部分数据状态重置为0:", s)
if i:
if i == "a":
m.add_index()
elif i == "g":
m.get_index()
if d:
if d == "d":
m.delete_dup()
elif d == "f":
m.find_duplicate()
if __name__ == '__main__':
run()
mongo helper的更多相关文章
- .net 操作MongoDB 基础
1. 下载驱动,最好使用 NuGet 下载,直接搜索MongoDB: 2. 引用相关驱动 3. 部分测试代码,主要是针对MongoDB的GridFS 文件存储来用 using Mongo.Model; ...
- MongoDB - The mongo Shell, Data Types in the mongo Shell
MongoDB BSON provides support for additional data types than JSON. Drivers provide native support fo ...
- MongoDB - The mongo Shell, Write Scripts for the mongo Shell
You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform a ...
- MongoDB - Introduction of the mongo Shell
Introduction The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mong ...
- 有用的 Mongo命令行 db.currentOp() db.collection.find().explain() - 摘自网络
在Heyzap 和 Bugsnag 我已经使用MongoDB超过一年了,我发现它是一个非常强大的数据库.和其他的数据库一样,它有一些缺陷,但是这里有一些东西我希望有人可以早一点告诉我的. 即使建立索引 ...
- mongo源码学习(四)invariant
前言 在看MongoDB源码的时候,经常会看到这个玩意儿:invariant. invariant的字面意思是:不变式. 在emacs上跳转到函数定义要安装一个插件,ggtags,费了老大劲儿.这都可 ...
- MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell
The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...
- 14.Iterate a Cursor in the mongo Shell-官方文档摘录
1 迭代游标 } ); while (myCursor.hasNext()) { print(tojson(myCursor.next())); } } ); myCursor.forEach(pri ...
- 4.Data Types in the mongo Shell-官方文档摘录
总结: 1.MongoDB 的BSON格式支持额外的数据类型 2 Date 对象内部存储64位字节存整数,存储使用NumberLong()这个类来存,使用NumberInt()存32位整数,128位十 ...
随机推荐
- 安装和使用pyltp
什么是pyltp: pyltp 是LTP的 Python 封装,提供了分词,词性标注,命名实体识别,依存句法分析,语义角色标注的功能. 安装 pyltp 测试环境:系统win10 64位, pytho ...
- python爬虫User Agent用户代理
UserAgent简介 UserAgent中文名为用户代理,是Http协议中的一部分,属于头域的组成部分,UserAgent也简称UA.它是一个特殊字符串头,是一种向访问网站提供你所使用的浏览器类型及 ...
- 【开发笔记】- 在Grails下查看打印真实的SQL
以往我们都是在hibernate里面开启sql,在grails里面只需要在 DataSource.groovy 里面的一个dataSource加入一个 logSql = true即可,但是这样加后发出 ...
- Objective-C之深浅拷贝
深拷贝(指针和指向都改变) , 浅拷贝(指针改变,指向不变) NSString *s1 = @"string"; NSLog(@"s1 : %p, %p, %@" ...
- nginx 常用的location rewrite proxy_pass
location 以 = 开头,表示精确匹配:如只匹配根目录结尾的请求,后面不能带任何字符串. 以^~ 开头,表示uri以某个常规字符串开头,如果匹配到,则不继续往下匹配.不是正则匹配 以~ 开头,表 ...
- Pandas 之 Series / DataFrame 初识
import numpy as np import pandas as pd Pandas will be a major tool of interest throughout(贯穿) much o ...
- Golang: 模拟搜索引擎爬虫
最近网站需要针对百度做 SEO 优化,用 Go 语言写了个测试程序,模拟一下百度的爬虫,看看返回的内容是否正确. 代码很简单,就是发送一个请求,把百度相关的信息放入请求头中即可,代码如下: packa ...
- PHP开发环境WAMP(Windows+Apache+MySQL+PHP)搭建
关于PHP开发环境这一块,网上有很多的集成环境可以使用,eg. WampServer,XAMPP,PhpStudy,Appserv ...用起来也很方便(但是我并没有比较过哪个更好用一点),但是呢,比 ...
- 自定义View(三),仿支付宝芝麻信用自定义控件
仿支付宝的芝麻信用仪表盘 实现的效果 实现的功能: 指针和数字动态改变 背景动态变化 没了... 代码如下 MyCustomView.java package com.example.testcust ...
- spark操作总结
一.sparkContext与sparkSession区别 任何Spark程序都是SparkContext开始的,SparkContext的初始化需要一个SparkConf对象,SparkConf包含 ...