elasticsearch.py 4.0 KB

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