databases.py 3.9 KB

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