Skip to content

Commit

Permalink
Create custom search field configuration and query
Browse files Browse the repository at this point in the history
  • Loading branch information
instification committed Mar 19, 2024
1 parent 686e6a7 commit 465f749
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/collective/elasticsearch/indexes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from Acquisition import aq_base
from Acquisition import aq_parent
from collective.elasticsearch import logger
from collective.elasticsearch.utils import getSearchFields
from datetime import date
from datetime import datetime
from DateTime import DateTime
Expand Down Expand Up @@ -214,14 +215,21 @@ def get_query(self, name, value):
# ES doesn't care about * like zope catalog does
clean_value = value.strip("*") if value else ""
queries = [{"match_phrase": {name: {"query": clean_value, "slop": 2}}}]
if name in ("Title", "SearchableText"):
for search in getSearchFields():
# we add the base search field above, skip duplicating here...
if search == name:
continue
# titles have most importance... we override here...
queries.append(
{"match_phrase_prefix": {"Title": {"query": clean_value, "boost": 2}}}
)
if name != "Title":
queries.append({"match": {name: {"query": clean_value}}})

if search == "Title":
queries.append(
{
"match_phrase_prefix": {
"Title": {"query": clean_value, "boost": 2}
}
}
)
else:
queries.append({"match": {search: {"query": clean_value}}})
return queries


Expand Down
7 changes: 7 additions & 0 deletions src/collective/elasticsearch/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ class IElasticSettings(Interface):
value_type=schema.TextLine(title="Index"),
)

search_fields = schema.Set(
title="Indexes which are used when performing a search. "
"Note, indexes should also be present in the Index setting.",
default={"Title", "Description", "SearchableText"},
value_type=schema.TextLine(title="Search Fields"),
)

sniff_on_start = schema.Bool(title="Sniff on start", default=False, required=False)

sniff_on_connection_fail = schema.Bool(
Expand Down
8 changes: 8 additions & 0 deletions src/collective/elasticsearch/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ def getESOnlyIndexes():
except (KeyError, AttributeError):
return {"Title", "Description", "SearchableText"}

def getSearchFields():
settings = get_settings()
try:
search_fields = settings.search_fields
return set(search_fields) if search_fields else set()
except (KeyError, AttributeError):
return {"Title", "SearchableText"}


def batches(data: list, size: int) -> List[List]:
"""Create a batch of lists from a base list."""
Expand Down

0 comments on commit 465f749

Please sign in to comment.