Skip to content

Commit c908174

Browse files
committed
Search: allow to search on different versions of subprojects
1 parent 765ebec commit c908174

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

readthedocs/search/faceted_search.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
MultiMatch,
1212
Nested,
1313
SimpleQueryString,
14+
Term,
1415
Wildcard,
1516
)
1617

@@ -35,12 +36,23 @@ class RTDFacetedSearch(FacetedSearch):
3536
'post_tags': ['</span>'],
3637
}
3738

38-
def __init__(self, query=None, filters=None, user=None, use_advanced_query=True, **kwargs):
39+
def __init__(
40+
self,
41+
query=None,
42+
filters=None,
43+
projects=None,
44+
user=None,
45+
use_advanced_query=True,
46+
**kwargs,
47+
):
3948
"""
4049
Pass in a user in order to filter search results by privacy.
4150
42-
If `use_advanced_query` is `True`,
43-
force to always use `SimpleQueryString` for the text query object.
51+
:param projects: A dictionary of project slugs mapped to a `VersionData` object.
52+
Results are filter with these values.
53+
54+
:param use_advanced_query: If `True` forces to always use
55+
`SimpleQueryString` for the text query object.
4456
4557
.. warning::
4658
@@ -50,6 +62,7 @@ def __init__(self, query=None, filters=None, user=None, use_advanced_query=True,
5062
self.user = user
5163
self.filter_by_user = kwargs.pop('filter_by_user', True)
5264
self.use_advanced_query = use_advanced_query
65+
self.projects = projects or {}
5366

5467
# Hack a fix to our broken connection pooling
5568
# This creates a new connection on every request,
@@ -259,7 +272,12 @@ def total_count(self):
259272
return s.hits.total
260273

261274
def query(self, search, query):
262-
"""Manipulates the query to support nested queries and a custom rank for pages."""
275+
"""
276+
Manipulates the query to support nested queries and a custom rank for pages.
277+
278+
If `self.projects` was given, we use it to filter the documents that
279+
match the same project and version.
280+
"""
263281
search = search.highlight_options(**self._highlight_options)
264282

265283
queries = self._get_queries(
@@ -280,8 +298,22 @@ def query(self, search, query):
280298
)
281299

282300
queries.extend([sections_nested_query, domains_nested_query])
301+
bool_query = Bool(should=queries)
302+
303+
if self.projects:
304+
versions_query = [
305+
Bool(
306+
must=[
307+
Term(project={'value': project}),
308+
Term(version={'value': version}),
309+
]
310+
)
311+
for project, version in self.projects.items()
312+
]
313+
bool_query = Bool(must=[bool_query, Bool(should=versions_query)])
314+
283315
final_query = FunctionScore(
284-
query=Bool(should=queries),
316+
query=bool_query,
285317
script_score=self._get_script_score(),
286318
)
287319
search = search.query(final_query)

0 commit comments

Comments
 (0)