Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions arches_search/utils/term_search/matching.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib.postgres.search import SearchQuery
from django.db.models import Q
from django.db.models import BooleanField, F, Func, Q, Value

from arches.app.models.models import ResourceInstance
from arches_search.models.models import TermSearch
Expand All @@ -8,6 +8,24 @@
)


def _contains_ignoring_case(term_text):
"""
`value ILIKE '%term%'`. Unlike icontains (UPPER(value) LIKE UPPER(...)), this is
served by the gin_trgm_ops index on TermSearch.value and can be BitmapOr'd
with the search_vector match.
"""
escaped_term = (
term_text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
)
return Func(
F("value"),
Value(f"%{escaped_term}%"),
arg_joiner=" ILIKE ",
template="(%(expressions)s)",
output_field=BooleanField(),
)


def build_term_match_filter(term_text, datatype=None):
"""
Q object matching TermSearch rows whose value either full-text-matches
Expand All @@ -16,7 +34,9 @@ def build_term_match_filter(term_text, datatype=None):
Pass datatype to additionally restrict matches to that TermSearch.datatype.
"""
full_text_query = SearchQuery(term_text, search_type="plain", config="english")
match_filter = Q(search_vector=full_text_query) | Q(value__icontains=term_text)
match_filter = Q(search_vector=full_text_query) | Q(
_contains_ignoring_case(term_text)
)
if datatype is not None:
match_filter &= Q(datatype=datatype)
return match_filter
Expand Down
125 changes: 93 additions & 32 deletions arches_search/utils/term_search/relationship_expansion.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,65 @@
import functools
import operator

from django.db.models import Q
from django.db.models import Expression, UUIDField
from django.db.models.expressions import RawSQL

from arches.app.models.models import ResourceInstance, ResourceXResource

MAX_ALLOWED_HOPS = 2
SEED_CTE_NAME = "term_direct_matches"
FRONTIER_CTE_PREFIX = "term_frontier_"


class MaterializedUnion(Expression):
"""
A parenthesized `WITH name AS MATERIALIZED (a UNION b ...) ... UNION ...`
subquery, for use as the right-hand side of an `__in` lookup.

Each named set is computed once however many times later sets reference
it (see set_reference), and sets are combined with UNION rather than OR'd
`IN` lists, so Postgres can plan the semi-joins instead of falling back to
per-row SubPlans.
"""

output_field = UUIDField()

def __init__(self, named_sets, final_set):
super().__init__()
self.named_sets = named_sets
self.final_set = final_set

# Wraps unhashable querysets; identity semantics are enough.
def __eq__(self, other):
return self is other

def __hash__(self):
return id(self)

@staticmethod
def _compile_union(querysets, connection):
sql_parts = []
params = []
for queryset in querysets:
sql, query_params = queryset.query.get_compiler(
connection=connection
).as_sql()
sql_parts.append(sql)
params.extend(query_params)
return " UNION ".join(sql_parts), params

def as_sql(self, compiler, connection):
cte_parts = []
params = []
for name, querysets in self.named_sets:
sql, set_params = self._compile_union(querysets, connection)
cte_parts.append(f"{name}(resourceinstanceid) AS MATERIALIZED ({sql})")
params.extend(set_params)
final_sql, final_params = self._compile_union(self.final_set, connection)
params.extend(final_params)
return f"(WITH {', '.join(cte_parts)} {final_sql})", params


def set_reference(name):
"""Right-hand side of an `__in` lookup selecting from a named set."""
return RawSQL(f"SELECT resourceinstanceid FROM {name}", [])


def expand_matches_via_relationships(
Expand All @@ -23,54 +77,61 @@ def expand_matches_via_relationships(
relations = readable_nodes.exclude_unreadable_relations(
ResourceXResource.objects.all()
)
seed_reference = set_reference(SEED_CTE_NAME)
named_sets = [
(
SEED_CTE_NAME,
[direct_match_resource_ids.values("resourceinstanceid")],
)
]
target_graph_match_sets = [
ResourceInstance.objects.filter(
resourceinstanceid__in=direct_match_resource_ids, graph_id=target_graphid
resourceinstanceid__in=seed_reference, graph_id=target_graphid
).values("resourceinstanceid")
]
traversal_frontier = (
ResourceInstance.objects.filter(
resourceinstanceid__in=direct_match_resource_ids

frontier_name = f"{FRONTIER_CTE_PREFIX}0"
named_sets.append(
(
frontier_name,
[
ResourceInstance.objects.filter(resourceinstanceid__in=seed_reference)
.exclude(graph_id=target_graphid)
.values("resourceinstanceid")
],
)
.exclude(graph_id=target_graphid)
.values("resourceinstanceid")
)

for hop_number in range(max_hops):
frontier_reference = set_reference(frontier_name)
target_graph_match_sets.append(
relations.filter(
to_resource__in=traversal_frontier,
to_resource_id__in=frontier_reference,
from_resource_graph_id=target_graphid,
).values("from_resource_id")
)
target_graph_match_sets.append(
relations.filter(
from_resource__in=traversal_frontier,
from_resource_id__in=frontier_reference,
to_resource_graph_id=target_graphid,
).values("to_resource_id")
)
if hop_number < max_hops - 1:
next_frontier_from = (
relations.filter(to_resource__in=traversal_frontier)
.exclude(from_resource_graph_id=target_graphid)
.values("from_resource_id")
frontier_name = f"{FRONTIER_CTE_PREFIX}{hop_number + 1}"
named_sets.append(
(
frontier_name,
[
relations.filter(to_resource_id__in=frontier_reference)
.exclude(from_resource_graph_id=target_graphid)
.values("from_resource_id"),
relations.filter(from_resource_id__in=frontier_reference)
.exclude(to_resource_graph_id=target_graphid)
.values("to_resource_id"),
],
)
)
next_frontier_to = (
relations.filter(from_resource__in=traversal_frontier)
.exclude(to_resource_graph_id=target_graphid)
.values("to_resource_id")
)
traversal_frontier = ResourceInstance.objects.filter(
Q(resourceinstanceid__in=next_frontier_from)
| Q(resourceinstanceid__in=next_frontier_to)
).values("resourceinstanceid")

return ResourceInstance.objects.filter(
functools.reduce(
operator.or_,
(
Q(resourceinstanceid__in=match_set)
for match_set in target_graph_match_sets
),
)
resourceinstanceid__in=MaterializedUnion(named_sets, target_graph_match_sets)
)
41 changes: 41 additions & 0 deletions tests/test_term_search_sql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""SQL-shape checks for term search; these compile queries without hitting the DB."""

import uuid

from django.db import connection
from django.test import SimpleTestCase

from arches_search.utils.readable_nodes import ReadableNodes
from arches_search.utils.term_search.matching import get_related_resources_by_text

# python manage.py test tests.test_term_search_sql --settings="tests.test_settings"


class TermSearchSqlTests(SimpleTestCase):
def compile_sql(self, terms, max_hops):
queryset = get_related_resources_by_text(
terms, uuid.uuid4(), ReadableNodes(None), max_hops=max_hops
)
return queryset.query.get_compiler(connection=connection).as_sql()

def test_term_subquery_is_materialized_once_per_term(self):
sql, _ = self.compile_sql(["beef"], max_hops=2)
self.assertEqual(sql.count('FROM "arches_search_terms"'), 1)
self.assertEqual(sql.count("AS MATERIALIZED"), 3)

def test_hops_are_combined_with_union(self):
sql, _ = self.compile_sql(["beef"], max_hops=2)
self.assertIn(" UNION ", sql)

def test_no_hops_has_no_relationship_tables(self):
sql, _ = self.compile_sql(["beef"], max_hops=0)
self.assertNotIn("resource_x_resource", sql)

def test_each_term_is_expanded_independently(self):
sql, _ = self.compile_sql(["beef", "pork"], max_hops=1)
self.assertEqual(sql.count('FROM "arches_search_terms"'), 2)

def test_substring_match_escapes_like_wildcards(self):
sql, params = self.compile_sql(["50%_off"], max_hops=0)
self.assertIn("ILIKE", sql)
self.assertIn("%50\\%\\_off%", params)
Loading