databases.py 3.8 KB

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