databases.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import bson
  2. import pymongo
  3. import redis
  4. import requests
  5. from elasticsearch import Elasticsearch
  6. from pymongo.collection import Collection
  7. from pymongo.uri_parser import SCHEME
  8. from config.load import mongo_conf, redis_conf, es_conf, analyze_url
  9. # ---------------------------------- mongo ----------------------------------
  10. MONGO_URI_CLIENTS = {} # a dictionary hold all client with uri as key
  11. def mongo_client(host=None, port=None, fork=False, **kwargs):
  12. if host is None:
  13. host = mongo_conf["host"]
  14. if port is None:
  15. port = mongo_conf["port"]
  16. if host is not None and host.startswith(SCHEME):
  17. uri = host
  18. else:
  19. uri = f'mongodb://{host}:{port}'
  20. if fork:
  21. return pymongo.MongoClient(uri, **kwargs)
  22. global MONGO_URI_CLIENTS
  23. matched_client = MONGO_URI_CLIENTS.get(uri)
  24. if matched_client is None:
  25. new_client = pymongo.MongoClient(uri, **kwargs)
  26. if new_client is not None:
  27. MONGO_URI_CLIENTS[uri] = new_client
  28. return new_client
  29. return matched_client
  30. def mongo_database(name: str, **kw):
  31. client = mongo_client(**kw)
  32. return client.get_database(name)
  33. def mongo_table(db: str, name: str, **kw):
  34. database = mongo_database(db, **kw)
  35. return database.get_collection(name)
  36. def int2long(param: int):
  37. """int 转换成 long """
  38. return bson.int64.Int64(param)
  39. def object_id(_id: str):
  40. return bson.objectid.ObjectId(_id)
  41. def update_one(collection: Collection, item):
  42. collection.update_one({'_id': item['_id']}, {'$set': item})
  43. def update_one_by_domain(collection: Collection, item):
  44. lst = []
  45. res = collection.find_one({'domain': item['domain']})
  46. if res is not None and item['origin'] not in res['origin']:
  47. lst.append(item['origin']) # 添加挖掘新成员
  48. lst.extend(res['origin']) # 合并已收录旧成员
  49. else:
  50. lst.append(item['origin'])
  51. item.update({'origin': lst})
  52. collection.update_one(
  53. {'domain': item['domain']},
  54. {'$set': item},
  55. upsert=True
  56. )
  57. def insert_one(collection: Collection, item):
  58. collection.insert_one(item)
  59. def insert_many(collection: Collection, items):
  60. for item in items:
  61. insert_one(collection, item)
  62. # ---------------------------------- es ----------------------------------
  63. def es_client(cfg=None):
  64. if cfg is None:
  65. cfg = es_conf
  66. return Elasticsearch([{"host": cfg['host'], "port": cfg['port']}])
  67. def es_participles_service(text: str):
  68. """
  69. 获取文本的分词列表
  70. :param text: 需要分词的文本
  71. :return: 分词列表
  72. """
  73. result = []
  74. params = {"text": text, "analyzer": "ik_smart"}
  75. res = requests.get(analyze_url, params=params, timeout=60)
  76. if res.status_code == 200:
  77. tokens = res.json().get('tokens', [])
  78. for x in tokens:
  79. if x["token"].encode('utf-8').isalpha():
  80. continue
  81. result.append(x["token"])
  82. return result
  83. def es_query(title: str, publish_time: int):
  84. """
  85. 查询es
  86. :param title: 标题
  87. :param publish_time: 发布时间
  88. :return:
  89. """
  90. client = es_client()
  91. stime = publish_time - 432000 # 往前推5天
  92. etime = publish_time + 432000
  93. conditions = []
  94. participles = es_participles_service(title)
  95. for word in participles:
  96. conditions.append({
  97. "multi_match": {
  98. "query": word,
  99. "type": "phrase",
  100. "fields": ["title"]
  101. }
  102. })
  103. conditions.append({"range": {"publishtime": {"from": stime, "to": etime}}})
  104. query = {
  105. "query": {
  106. "bool": {
  107. "must": conditions,
  108. "minimum_should_match": 1
  109. }
  110. }
  111. }
  112. result = client.search(index=es_conf['db'], body=query, request_timeout=100)
  113. count = len(result['hits']['hits'])
  114. return count
  115. # ---------------------------------- redis ----------------------------------
  116. def redis_client(cfg=None, host=None, port=None, db=None, password=None):
  117. _cfg = (cfg or redis_conf)
  118. host = (host or _cfg['host'])
  119. port = (port or _cfg['port'])
  120. password = (password or _cfg['pwd'])
  121. db = (db or _cfg['db'])
  122. return redis.StrictRedis(host=host,
  123. port=port,
  124. password=password,
  125. db=db, decode_responses=True)