Skip to content

Commit

Permalink
OpenConceptLab/ocl_issues#1587 | must have in search using quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
snyaggarwal committed Aug 24, 2023
1 parent 8f896cc commit 4ad762b
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions core/common/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import re
from email.mime.image import MIMEImage

import markdown
Expand Down Expand Up @@ -206,9 +207,24 @@ def clean_fields(self, fields):
return fields

def get_search_string(self, lower=True, decode=True):
search_str = self.request.query_params.dict().get(SEARCH_PARAM, '').strip()
search_str = self.get_raw_search_string().replace('"', '').replace("'", "")
return CustomESSearch.get_search_string(search_str, lower=lower, decode=decode)

def get_raw_search_string(self):
return self.request.query_params.dict().get(SEARCH_PARAM, '').strip()

def get_search_must_haves(self):
pattern = r'"([^"]*)"'
matches = compact(re.findall(pattern, self.get_raw_search_string()))
result = []
for match in matches:
match = match.strip()
if ' ' in match:
result += match.split()
else:
result.append(match)
return set(result)

@property
def is_fuzzy_search(self):
return self.request.query_params.dict().get('fuzzy', None) in get_truthy_values()
Expand Down Expand Up @@ -254,10 +270,10 @@ def get_fuzzy_search_criterion(self, boost_divide_by=10, expansions=5):
expansions=expansions
)

def get_wildcard_search_criterion(self):
def get_wildcard_search_criterion(self, search_str=None):
fields = self.get_wildcard_search_fields()
return CustomESSearch.get_wildcard_match_criterion(
search_str=self.get_search_string(),
search_str=search_str or self.get_search_string(),
fields=fields
), fields.keys()

Expand Down Expand Up @@ -620,6 +636,12 @@ def __search_results(self): # pylint: disable=too-many-branches,too-many-locals
criterion |= self.get_fuzzy_search_criterion(boost_divide_by=10000, expansions=2)

results = results.query(criterion)
must_have_criterion = None
for must_have in self.get_search_must_haves():
criteria, _ = self.get_wildcard_search_criterion(f"*{must_have}*")
must_have_criterion = criteria if must_have_criterion is None else must_have_criterion & criteria
if must_have_criterion is not None:
results = results.filter(must_have_criterion)

if extras_fields:
fields += list(extras_fields.keys())
Expand Down

0 comments on commit 4ad762b

Please sign in to comment.