redis_server.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Redis is an open source (BSD licensed), in-memory data structure (key value
  3. based) store. Before configuring the ``redis_server`` engine, you must install
  4. the dependency redis_.
  5. Configuration
  6. =============
  7. Select a database to search in and set its index in the option ``db``. You can
  8. either look for exact matches or use partial keywords to find what you are
  9. looking for by configuring ``exact_match_only``.
  10. Example
  11. =======
  12. Below is an example configuration:
  13. .. code:: yaml
  14. # Required dependency: redis
  15. - name: myredis
  16. shortcut : rds
  17. engine: redis_server
  18. exact_match_only: false
  19. host: '127.0.0.1'
  20. port: 6379
  21. enable_http: true
  22. password: ''
  23. db: 0
  24. Implementations
  25. ===============
  26. """
  27. import redis # pylint: disable=import-error
  28. from searx.result_types import EngineResults
  29. engine_type = 'offline'
  30. # redis connection variables
  31. host = '127.0.0.1'
  32. port = 6379
  33. password = ''
  34. db = 0
  35. # engine specific variables
  36. paging = False
  37. exact_match_only = True
  38. _redis_client = None
  39. def init(_engine_settings):
  40. global _redis_client # pylint: disable=global-statement
  41. _redis_client = redis.StrictRedis(
  42. host=host,
  43. port=port,
  44. db=db,
  45. password=password or None,
  46. decode_responses=True,
  47. )
  48. def search(query, _params) -> EngineResults:
  49. res = EngineResults()
  50. if not exact_match_only:
  51. for kvmap in search_keys(query):
  52. res.add(res.types.KeyValue(kvmap=kvmap))
  53. return res
  54. kvmap: dict[str, str] = _redis_client.hgetall(query)
  55. if kvmap:
  56. res.add(res.types.KeyValue(kvmap=kvmap))
  57. elif " " in query:
  58. qset, rest = query.split(" ", 1)
  59. for row in _redis_client.hscan_iter(qset, match='*{}*'.format(rest)):
  60. res.add(res.types.KeyValue(kvmap={row[0]: row[1]}))
  61. return res
  62. def search_keys(query) -> list[dict]:
  63. ret = []
  64. for key in _redis_client.scan_iter(match='*{}*'.format(query)):
  65. key_type = _redis_client.type(key)
  66. res = None
  67. if key_type == 'hash':
  68. res = _redis_client.hgetall(key)
  69. elif key_type == 'list':
  70. res = dict(enumerate(_redis_client.lrange(key, 0, -1)))
  71. if res:
  72. res['redis_key'] = key
  73. ret.append(res)
  74. return ret