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
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ A custom datatype needs four things to work with Advanced Search:
3. An indexer, so tile values get written into that table.
4. Optionally, an operand normalizer, so values submitted from the UI are shaped correctly before comparison.

A custom datatype gets sorting for free once it has an indexer: an ordering reads whichever table that indexer writes to. See [Sorting a node value](#sorting-a-node-value).

### Indexers

Subclass `arches_search.indexing.base.BaseIndexing`, point `self.datatype` at your datatype, and return the rows to write from `index(self, tile, node)`:
Expand Down Expand Up @@ -943,15 +945,32 @@ Values are always a list, so a client never has to branch on cardinality:
| ---------------- | ------------------------------------------------------------------------- | --------------------------- |
| `primary_name` | the resource's descriptor name in the active language, case-insensitively | — |
| `created_time` | `createdtime`, the resource's creation timestamp | — |
| `NODE` | a projected node (tile) value | `graph_slug`, `node_alias` |
| `NODE` | a node's indexed value | `graph_slug`, `node_alias` |
| `RESOURCE_FIELD` | one of the resource's own columns | `field` |

`NODE` and `RESOURCE_FIELD` are the same tokens a clause subject uses.
`primary_name` and `created_time` name no subject, so they stay lowercase.

Ordering by a node value annotates it for you; it does not have to appear in
`additional_data` as well. A node the requester may not read is skipped rather
than reported, matching how projection omits it.
A node does not have to appear in `additional_data` to be sorted on. A node
the requester may not read is skipped rather than reported, matching how
projection omits it.

#### Sorting a node value

A `NODE` sort reads the search table the node is indexed into, the same table
filtering uses, and orders by the indexed value. The query itself does no
per-row work.

The table depends on the datatype. Numbers sort off `NumericSearch` and dates
off `DateSearch`, each in its own type, so 9 comes before 10. Text sorts off
`TermSearch`, lowercased first. Reference and concept nodes sort by the
preferred label in the active language: their indexers record the language and
valuetype of every label, and the sort asks for the preferred one.

A node under a cardinality-n nodegroup has more than one indexed row per resource.
Those sort by the first tile, ordered by `parenttile`, `sortorder`, then `tileid`.
The last key matters because tiles do share a `sortorder` in real data, and without
it the row chosen varies between queries. A node with no indexed rows sorts last.

Every sort is followed by a tie-break on `resourceinstanceid`, so paging stays
stable when the sort key ties. Foreign keys order by the related record's label
Expand Down
11 changes: 11 additions & 0 deletions arches_search/indexing/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,14 @@ def __init__(self):

def index(self, tile, node):
pass

def sort_row_filters(self) -> dict:
"""
Field lookups that pick out the single row to sort by, for an indexer
that potentially writes several rows per value.

A reference writes a row per label, so it returns
{"valuetype": "prefLabel"}. An indexer writing one row per value has
nothing to narrow, and returns nothing.
"""
return {}
35 changes: 17 additions & 18 deletions arches_search/indexing/indexers/concept.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from django.contrib.postgres.search import SearchVector
from arches.app.datatypes.datatypes import DataTypeFactory, BaseDataType
from arches.app.models.models import Language
from arches_search.models.models import DateRangeSearch, TermSearch, UUIDSearch

from arches_search.indexing.base import BaseIndexing
Expand All @@ -10,29 +8,30 @@ class ConceptIndexing(BaseIndexing):
def __init__(self):
super().__init__()
self.datatype: BaseDataType = DataTypeFactory().get_instance("concept")
self.languages: dict[str, Language] = {}

def _set_languages(self):
if not self.languages:
for l_obj in Language.objects.all():
self.languages[l_obj.code] = l_obj
def sort_row_filters(self) -> dict:
"""Sort by the preferred label, not by an alternate one."""
return {"valuetype": "prefLabel"}

def index(self, tile, node):
nodeid = str(node.nodeid)
document = {"domains": [], "strings": [], "date_ranges": []}
self.datatype.append_to_document(document, tile.data[nodeid], node, tile)
search_items = []
for string in document["strings"]:
if string["string"] is not None:
string_search = TermSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
value=string["string"],
)
search_items.append(string_search)

for valueid in self.datatype.get_nodevalues(tile.data[nodeid]):
concept_value = self.datatype.get_value(valueid)
string_search = TermSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
language=concept_value.language_id or "",
valuetype=concept_value.valuetype_id,
value=concept_value.value,
)
search_items.append(string_search)

for concept in document["domains"]:
for id in [concept["conceptid"], concept["valueid"]]:
Expand Down
2 changes: 0 additions & 2 deletions arches_search/indexing/indexers/concept_list.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from arches.app.datatypes.datatypes import DataTypeFactory, BaseDataType
from arches.app.models.models import Language

from arches_search.indexing.indexers.concept import ConceptIndexing

Expand All @@ -8,4 +7,3 @@ class ConceptListIndexing(ConceptIndexing):
def __init__(self):
super().__init__()
self.datatype: BaseDataType = DataTypeFactory().get_instance("concept-list")
self.languages: dict[str, Language] = {}
72 changes: 37 additions & 35 deletions arches_search/indexing/indexers/reference.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from django.contrib.postgres.search import SearchVector
from arches.app.datatypes.datatypes import DataTypeFactory, BaseDataType
from arches.app.models.models import Language
from arches_search.models.models import TermSearch, UUIDSearch

from arches_search.indexing.base import BaseIndexing
Expand All @@ -10,42 +8,46 @@ class ReferenceIndexing(BaseIndexing):
def __init__(self):
super().__init__()
self.datatype: BaseDataType = DataTypeFactory().get_instance("reference")
self.languages: dict[str, Language] = {}

def _set_languages(self):
if not self.languages:
for l_obj in Language.objects.all():
self.languages[l_obj.code] = l_obj
def sort_row_filters(self) -> dict:
"""Sort by the preferred label, not by an alternate one."""
return {"valuetype": "prefLabel"}

def index(self, tile, node):
nodeid = str(node.nodeid)
self._set_languages()
document = {"strings": [], "references": []}
self.datatype.append_to_document(document, tile.data[nodeid], node, tile)
"""
A row per label, carrying the language and valuetype it declares.

Read from the tile rather than through append_to_document(), which
flattens labels to bare strings and so loses both.
"""
search_items = []
for string in document["strings"]:
if string["string"] is not None:
string_search = TermSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
language=node.config.lang,
value=string["string"],
)
search_items.append(string_search)

for reference in document["references"]:
if reference["id"] is not None:
uuid_search = UUIDSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
value=reference["id"],
)
search_items.append(uuid_search)

for reference in tile.data[str(node.nodeid)]:
for label in reference["labels"]:
if label["value"] is not None:
search_items.append(
TermSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
language=label["language_id"],
valuetype=label["valuetype_id"],
value=label["value"],
)
)

if label["id"] is not None:
search_items.append(
UUIDSearch(
node_alias=node.alias,
tileid_id=tile.tileid,
resourceinstanceid_id=tile.resourceinstance_id,
datatype=self.datatype.datatype_name,
graph_slug=node.graph.slug,
value=label["id"],
)
)

return search_items
18 changes: 18 additions & 0 deletions arches_search/migrations/0024_term_valuetype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 6.1 on 2026-09-28 15:34

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("arches_search", "0023_seed_resource_field_facets"),
]

operations = [
migrations.AddField(
model_name="termsearch",
name="valuetype",
field=models.TextField(default=""),
),
]
1 change: 1 addition & 0 deletions arches_search/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ class TermSearch(models.Model):
node_alias = models.TextField()
language = models.TextField()
datatype = models.TextField()
valuetype = models.TextField(default="")
value = models.TextField()
search_vector = models.GeneratedField(
null=True,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ def get_value_model_for_datatype(self, datatype_name: str) -> Any:

return model_class

def get_sort_model_for_datatype(self, datatype_name: str) -> Any:
"""
The model an ordering reads, or None where the datatype has nothing
worth ordering by.
"""
value_models = [
model_class
for model_class in self._datatype_to_model_classes.get(datatype_name, [])
if self._model_has_field(model_class, "value")
and not self._value_field_is_uuid(model_class)
]

if len(value_models) != 1:
return None

return value_models[0]

def get_relationship_model_for_datatype(self, datatype_name: str) -> Any:
model_class = self._datatype_to_relationship_model_class.get(datatype_name)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
result nests them under node_values and resource_fields instead of one flat map.
"""

from typing import Any, Dict, Iterable, List, Optional
from typing import Any, Dict, List, Optional

from django.core.exceptions import ValidationError
from django.db.models import QuerySet
Expand Down Expand Up @@ -80,15 +80,11 @@ def __init__(
self,
additional_data: Optional[List[Dict[str, Any]]],
readable_nodes: ReadableNodes,
also_project_nodes: Iterable[NodeKey] = (),
):
entries = additional_data or []
node_keys = node_values.keys(
[entry for entry in entries if entry.get("type") == SUBJECT_TYPE_NODE]
)
for node_key in also_project_nodes:
if node_key not in node_keys:
node_keys.append(node_key)

self.nodes_by_key = node_values.resolve(node_keys, readable_nodes)
self.fields_by_name = resource_fields.resolve(
Expand Down
9 changes: 4 additions & 5 deletions arches_search/utils/search/additional_data/node_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

A search result row is a ResourceInstance, so a node's value is not on the row:
it lives in tile data. Filtering already handles that with existence subqueries,
but an Exists() answers only "does a matching value exist" -- it cannot be
selected or ordered by. This module annotates the *value itself* onto the result
queryset using the querysets extension's node-value expression, which makes the
same annotation usable for both display and sorting.
but an Exists() answers only "does a matching value exist" it cannot be
selected. This module annotates the *value itself* onto the result queryset
using arches_querysets' node-value expression. Ordering does not read these
columns: it joins the indexed rows instead, see search.sorting.

The annotation is applied before pagination so ordering applies to the whole
result set rather than to one page, and so the values arrive with the page
Expand All @@ -19,7 +19,6 @@

from typing import Any, Dict, Iterable, List, Optional, Tuple


from arches.app.models.models import Node

from arches.extensions.querysets.models import TileTree
Expand Down
13 changes: 6 additions & 7 deletions arches_search/utils/search/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from arches.app.utils.betterJSONSerializer import JSONSerializer

from arches_search.utils.readable_nodes import ReadableNodes
from arches_search.utils.search.additional_data import node_values
from arches_search.utils.search.additional_data.additional_data import (
AdditionalData,
validate_additional_data,
Expand Down Expand Up @@ -55,16 +56,14 @@ def execute_search(
payload, user, pre_filter=pre_filter, readable_nodes=readable_nodes
).compile()

additional_data = AdditionalData(
search_request.additional_data,
readable_nodes,
# Ordering by a node value needs it annotated too.
also_project_nodes=_node_keys_an_ordering_needs(sort_resolver),
additional_data = AdditionalData(search_request.additional_data, readable_nodes)

sort_nodes = node_values.resolve(
_node_keys_an_ordering_needs(sort_resolver), readable_nodes
)

results_queryset = sort_resolver.apply(
additional_data.annotate(search_result.results),
node_column_annotations=additional_data.node_annotation_names,
additional_data.annotate(search_result.results), sort_nodes=sort_nodes
)

paginator = Paginator(results_queryset, search_request.page_size)
Expand Down
Loading
Loading