elasticsearch.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """.. sidebar:: info
  3. - :origin:`elasticsearch.py <searx/engines/elasticsearch.py>`
  4. - `Elasticsearch <https://www.elastic.co/elasticsearch/>`_
  5. - `Elasticsearch Guide
  6. <https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
  7. - `Install Elasticsearch
  8. <https://www.elastic.co/guide/en/elasticsearch/reference/current/install-elasticsearch.html>`_
  9. Elasticsearch_ supports numerous ways to query the data it is storing. At the
  10. moment the engine supports the most popular search methods (``query_type``):
  11. - ``match``,
  12. - ``simple_query_string``,
  13. - ``term`` and
  14. - ``terms``.
  15. If none of the methods fit your use case, you can select ``custom`` query type
  16. and provide the JSON payload to submit to Elasticsearch in
  17. ``custom_query_json``.
  18. Example
  19. =======
  20. The following is an example configuration for an Elasticsearch_ instance with
  21. authentication configured to read from ``my-index`` index.
  22. .. code:: yaml
  23. - name: elasticsearch
  24. shortcut: es
  25. engine: elasticsearch
  26. base_url: http://localhost:9200
  27. username: elastic
  28. password: changeme
  29. index: my-index
  30. query_type: match
  31. # custom_query_json: '{ ... }'
  32. enable_http: true
  33. """
  34. from json import loads, dumps
  35. from searx.exceptions import SearxEngineAPIException
  36. base_url = 'http://localhost:9200'
  37. username = ''
  38. password = ''
  39. index = ''
  40. search_url = '{base_url}/{index}/_search'
  41. query_type = 'match'
  42. custom_query_json = {}
  43. show_metadata = False
  44. categories = ['general']
  45. def init(engine_settings):
  46. if 'query_type' in engine_settings and engine_settings['query_type'] not in _available_query_types:
  47. raise ValueError('unsupported query type', engine_settings['query_type'])
  48. if index == '':
  49. raise ValueError('index cannot be empty')
  50. def request(query, params):
  51. if query_type not in _available_query_types:
  52. return params
  53. if username and password:
  54. params['auth'] = (username, password)
  55. params['url'] = search_url.format(base_url=base_url, index=index)
  56. params['method'] = 'GET'
  57. params['data'] = dumps(_available_query_types[query_type](query))
  58. params['headers']['Content-Type'] = 'application/json'
  59. return params
  60. def _match_query(query):
  61. """
  62. The standard for full text queries.
  63. searx format: "key:value" e.g. city:berlin
  64. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
  65. """
  66. try:
  67. key, value = query.split(':')
  68. except Exception as e:
  69. raise ValueError('query format must be "key:value"') from e
  70. return {"query": {"match": {key: {'query': value}}}}
  71. def _simple_query_string_query(query):
  72. """
  73. Accepts query strings, but it is less strict than query_string
  74. The field used can be specified in index.query.default_field in Elasticsearch.
  75. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
  76. """
  77. return {'query': {'simple_query_string': {'query': query}}}
  78. def _term_query(query):
  79. """
  80. Accepts one term and the name of the field.
  81. searx format: "key:value" e.g. city:berlin
  82. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
  83. """
  84. try:
  85. key, value = query.split(':')
  86. except Exception as e:
  87. raise ValueError('query format must be key:value') from e
  88. return {'query': {'term': {key: value}}}
  89. def _terms_query(query):
  90. """
  91. Accepts multiple terms and the name of the field.
  92. searx format: "key:value1,value2" e.g. city:berlin,paris
  93. REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
  94. """
  95. try:
  96. key, values = query.split(':')
  97. except Exception as e:
  98. raise ValueError('query format must be key:value1,value2') from e
  99. return {'query': {'terms': {key: values.split(',')}}}
  100. def _custom_query(query):
  101. key, value = query.split(':')
  102. custom_query = custom_query_json
  103. for query_key, query_value in custom_query.items():
  104. if query_key == '{{KEY}}':
  105. custom_query[key] = custom_query.pop(query_key)
  106. if query_value == '{{VALUE}}':
  107. custom_query[query_key] = value
  108. return custom_query
  109. def response(resp):
  110. results = []
  111. resp_json = loads(resp.text)
  112. if 'error' in resp_json:
  113. raise SearxEngineAPIException(resp_json['error'])
  114. for result in resp_json['hits']['hits']:
  115. r = {key: str(value) if not key.startswith('_') else value for key, value in result['_source'].items()}
  116. r['template'] = 'key-value.html'
  117. if show_metadata:
  118. r['metadata'] = {'index': result['_index'], 'id': result['_id'], 'score': result['_score']}
  119. results.append(r)
  120. return results
  121. _available_query_types = {
  122. # Full text queries
  123. # https://www.elastic.co/guide/en/elasticsearch/reference/current/full-text-queries.html
  124. 'match': _match_query,
  125. 'simple_query_string': _simple_query_string_query,
  126. # Term-level queries
  127. # https://www.elastic.co/guide/en/elasticsearch/reference/current/term-level-queries.html
  128. 'term': _term_query,
  129. 'terms': _terms_query,
  130. # Query JSON defined by the instance administrator.
  131. 'custom': _custom_query,
  132. }