.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mongodb.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""MongoDB_ is a document based database program that handles JSON like data.
3Before configuring the ``mongodb`` engine, you must install the dependency
4pymongo_.
5
6Configuration
7=============
8
9In order to query MongoDB_, you have to select a ``database`` and a
10``collection``. Furthermore, you have to select a ``key`` that is going to be
11searched. MongoDB_ also supports the option ``exact_match_only``, so configure
12it as you wish.
13
14Example
15=======
16
17Below is an example configuration for using a MongoDB collection:
18
19.. code:: yaml
20
21 # MongoDB engine
22 # Required dependency: pymongo
23
24 - name: mymongo
25 engine: mongodb
26 shortcut: md
27 exact_match_only: false
28 host: '127.0.0.1'
29 port: 27017
30 enable_http: true
31 results_per_page: 20
32 database: 'business'
33 collection: 'reviews' # name of the db collection
34 key: 'name' # key in the collection to search for
35
36Implementations
37===============
38
39"""
40
41import re
42
43try:
44 from pymongo import MongoClient # type: ignore
45except ImportError:
46 # import error is ignored because the admin has to install pymongo manually
47 # to use the engine
48 pass
49
50
51engine_type = 'offline'
52
53# mongodb connection variables
54host = '127.0.0.1'
55port = 27017
56username = ''
57password = ''
58database = None
59collection = None
60key = None
61
62# engine specific variables
63paging = True
64results_per_page = 20
65exact_match_only = False
66result_template = 'key-value.html'
67
68_client = None
69
70
71def init(_):
72 connect()
73
74
75def connect():
76 global _client # pylint: disable=global-statement
77 kwargs = {'port': port}
78 if username:
79 kwargs['username'] = username
80 if password:
81 kwargs['password'] = password
82 _client = MongoClient(host, **kwargs)[database][collection]
83
84
85def search(query, params):
86 results = []
87 if exact_match_only:
88 q = {'$eq': query}
89 else:
90 _re = re.compile('.*{0}.*'.format(re.escape(query)), re.I | re.M)
91 q = {'$regex': _re}
92
93 query = _client.find({key: q}).skip((params['pageno'] - 1) * results_per_page).limit(results_per_page)
94
95 results.append({'number_of_results': query.count()})
96 for r in query:
97 del r['_id']
98 r = {str(k): str(v) for k, v in r.items()}
99 r['template'] = result_template
100 results.append(r)
101
102 return results