databases.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import bson
  2. import pymongo
  3. import redis
  4. import requests
  5. from elasticsearch import Elasticsearch
  6. from config.load import mongo_conf, redis_conf, es_conf, analyze_url
  7. # ---------------------------------- mongo ----------------------------------
  8. def mongo_client(cfg=None):
  9. if cfg is None:
  10. cfg = mongo_conf
  11. return pymongo.MongoClient(host=cfg['host'], port=cfg['port'])
  12. def mongo_database(db: str):
  13. client = mongo_client()
  14. return client[db]
  15. def mongo_table(db: str, coll: str):
  16. client = mongo_client()
  17. return client[db][coll]
  18. def int2long(param: int):
  19. """int 转换成 long """
  20. return bson.int64.Int64(param)
  21. def object_id(_id: str):
  22. return bson.objectid.ObjectId(_id)
  23. # ---------------------------------- es ----------------------------------
  24. def es_client(cfg=None):
  25. if cfg is None:
  26. cfg = es_conf
  27. return Elasticsearch([{"host": cfg['host'], "port": cfg['port']}])
  28. def es_participles_service(text: str):
  29. """
  30. 获取文本的分词列表
  31. :param text: 需要分词的文本
  32. :return: 分词列表
  33. """
  34. result = []
  35. params = {"text": text, "analyzer": "ik_smart"}
  36. res = requests.get(analyze_url, params=params, timeout=60)
  37. if res.status_code == 200:
  38. tokens = res.json().get('tokens', [])
  39. for x in tokens:
  40. if x["token"].encode('utf-8').isalpha():
  41. continue
  42. result.append(x["token"])
  43. return result
  44. def es_query(title: str, publish_time: int):
  45. """
  46. 查询es
  47. :param title: 标题
  48. :param publish_time: 发布时间
  49. :return:
  50. """
  51. client = es_client()
  52. stime = publish_time - 432000 # 往前推5天
  53. etime = publish_time + 432000
  54. conditions = []
  55. participles = es_participles_service(title)
  56. for word in participles:
  57. conditions.append({
  58. "multi_match": {
  59. "query": word,
  60. "type": "phrase",
  61. "fields": ["title"]
  62. }
  63. })
  64. conditions.append({
  65. "range": {"publishtime": {"from": stime, "to": etime}}
  66. })
  67. query = {
  68. "query": {
  69. "bool": {
  70. "must": conditions,
  71. "minimum_should_match": 1
  72. }
  73. }
  74. }
  75. result = client.search(index='bidding', body=query, request_timeout=100)
  76. count = len(result['hits']['hits'])
  77. return count
  78. # ---------------------------------- redis ----------------------------------
  79. def redis_client(cfg=None):
  80. if cfg is None:
  81. cfg = redis_conf
  82. pool = redis.ConnectionPool(
  83. host=cfg['host'],
  84. port=cfg['port'],
  85. password=cfg['pwd'],
  86. db=cfg['db']
  87. )
  88. return redis.Redis(connection_pool=pool, decode_responses=True)