elasticsearch.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Elasticsearch
  4. """
  5. from json import loads, dumps
  6. from searx.exceptions import SearxEngineAPIException
  7. base_url = 'http://localhost:9200'
  8. username = ''
  9. password = ''
  10. index = ''
  11. search_url = base_url + '/' + index + '/_search'
  12. query_type = 'match'
  13. custom_query_json = {}
  14. show_metadata = False
  15. categories = ['general']
  16. def init(engine_settings):
  17. if 'query_type' in engine_settings and engine_settings['query_type'] not in _available_query_types:
  18. raise ValueError('unsupported query type', engine_settings['query_type'])
  19. if index == '':
  20. raise ValueError('index cannot be empty')
  21. def request(query, params):
  22. if query_type not in _available_query_types:
  23. return params
  24. if username and password:
  25. params['auth'] = (username, password)
  26. params['url'] = search_url
  27. params['method'] = 'GET'
  28. params['data'] = dumps(_available_query_types[query_type](query))
  29. params['headers']['Content-Type'] = 'application/json'
  30. return params
  31. def _match_query(query):
  32. """
  33. The standard for full text queries.
  34. searx format: "key:value" e.g. city:berlin
  35. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
  36. """
  37. try:
  38. key, value = query.split(':')
  39. except Exception as e:
  40. raise ValueError('query format must be "key:value"') from e
  41. return {"query": {"match": {key: {'query': value}}}}
  42. def _simple_query_string_query(query):
  43. """
  44. Accepts query strings, but it is less strict than query_string
  45. The field used can be specified in index.query.default_field in Elasticsearch.
  46. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
  47. """
  48. return {'query': {'simple_query_string': {'query': query}}}
  49. def _term_query(query):
  50. """
  51. Accepts one term and the name of the field.
  52. searx format: "key:value" e.g. city:berlin
  53. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
  54. """
  55. try:
  56. key, value = query.split(':')
  57. except Exception as e:
  58. raise ValueError('query format must be key:value') from e
  59. return {'query': {'term': {key: value}}}
  60. def _terms_query(query):
  61. """
  62. Accepts multiple terms and the name of the field.
  63. searx format: "key:value1,value2" e.g. city:berlin,paris
  64. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
  65. """
  66. try:
  67. key, values = query.split(':')
  68. except Exception as e:
  69. raise ValueError('query format must be key:value1,value2') from e
  70. return {'query': {'terms': {key: values.split(',')}}}
  71. def _custom_query(query):
  72. key, value = query.split(':')
  73. custom_query = custom_query_json
  74. for query_key, query_value in custom_query.items():
  75. if query_key == '{{KEY}}':
  76. custom_query[key] = custom_query.pop(query_key)
  77. if query_value == '{{VALUE}}':
  78. custom_query[query_key] = value
  79. return custom_query
  80. def response(resp):
  81. results = []
  82. resp_json = loads(resp.text)
  83. if 'error' in resp_json:
  84. raise SearxEngineAPIException(resp_json['error'])
  85. for result in resp_json['hits']['hits']:
  86. r = {key: str(value) if not key.startswith('_') else value for key, value in result['_source'].items()}
  87. r['template'] = 'key-value.html'
  88. if show_metadata:
  89. r['metadata'] = {'index': result['_index'],
  90. 'id': result['_id'],
  91. 'score': result['_score']}
  92. results.append(r)
  93. return results
  94. _available_query_types = {
  95. # Full text queries
  96. # https://www.elastic.co/guide/en/elasticsearch/reference/current/full-text-queries.html
  97. 'match': _match_query,
  98. 'simple_query_string': _simple_query_string_query,
  99. # Term-level queries
  100. # https://www.elastic.co/guide/en/elasticsearch/reference/current/term-level-queries.html
  101. 'term': _term_query,
  102. 'terms': _terms_query,
  103. # Query JSON defined by the instance administrator.
  104. 'custom': _custom_query,
  105. }