databases.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. items = collection.find_one({'domain': item['domain']})
  46. if items is not None:
  47. origin = items.get('origin', [])
  48. if item['origin'] not in origin:
  49. lst.append(item['origin'])
  50. lst.extend(origin)
  51. else:
  52. lst.append(item['origin'])
  53. item.update({'origin': lst})
  54. collection.update_one(
  55. {'domain': item['domain']},
  56. {'$set': item},
  57. upsert=True
  58. )
  59. def insert_one(collection: Collection, item):
  60. collection.insert_one(item)
  61. def insert_many(collection: Collection, items):
  62. for item in items:
  63. insert_one(collection, item)
  64. # ---------------------------------- es ----------------------------------
  65. def es_client(cfg=None):
  66. if cfg is None:
  67. cfg = es_conf
  68. return Elasticsearch([{"host": cfg['host'], "port": cfg['port']}])
  69. def es_participles_service(text: str):
  70. """
  71. 获取文本的分词列表
  72. :param text: 需要分词的文本
  73. :return: 分词列表
  74. """
  75. result = []
  76. params = {"text": text, "analyzer": "ik_smart"}
  77. res = requests.get(analyze_url, params=params, timeout=60)
  78. if res.status_code == 200:
  79. tokens = res.json().get('tokens', [])
  80. for x in tokens:
  81. if x["token"].encode('utf-8').isalpha():
  82. continue
  83. result.append(x["token"])
  84. return result
  85. def es_query(title: str, publish_time: int):
  86. """
  87. 查询es
  88. :param title: 标题
  89. :param publish_time: 发布时间
  90. :return:
  91. """
  92. client = es_client()
  93. stime = publish_time - 432000 # 往前推5天
  94. etime = publish_time + 432000
  95. conditions = []
  96. participles = es_participles_service(title)
  97. for word in participles:
  98. conditions.append({
  99. "multi_match": {
  100. "query": word,
  101. "type": "phrase",
  102. "fields": ["title"]
  103. }
  104. })
  105. conditions.append({"range": {"publishtime": {"from": stime, "to": etime}}})
  106. query = {
  107. "query": {
  108. "bool": {
  109. "must": conditions,
  110. "minimum_should_match": 1
  111. }
  112. }
  113. }
  114. result = client.search(index=es_conf['db'], body=query, request_timeout=100)
  115. count = len(result['hits']['hits'])
  116. return count
  117. # ---------------------------------- redis ----------------------------------
  118. def redis_client(cfg=None, host=None, port=None, db=None, password=None):
  119. _cfg = (cfg or redis_conf)
  120. host = (host or _cfg['host'])
  121. port = (port or _cfg['port'])
  122. password = (password or _cfg['pwd'])
  123. db = (db or _cfg['db'])
  124. pool = redis.ConnectionPool(
  125. host=host,
  126. port=port,
  127. password=password,
  128. db=db
  129. )
  130. return redis.Redis(connection_pool=pool, decode_responses=True)