Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search): honor property_filters in unified search query (#4234)

gbirman8adcaaf47c29
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
index e9da217979..cf77c28e26 100644
--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
@@ -21,10 +21,36 @@ import {
} from '@queries/soup/search';
import type {
EntityFilters,
+ PropertyFilter,
UnifiedSearchRequest,
} from '@service-search/generated/models';
import { type Accessor, createMemo, on, type Setter } from 'solid-js';
+// Map the tasks-view property filters (status/priority/assignee/custom) into the
+// search request shape, mirroring the soup path so search and soup agree. Values
+// are grouped by property id: multiple values on one property are OR'd (a task
+// matches any of them), and different properties are AND'd. Select options go to
+// option_ids, entity refs to entity_ids.
+function includePropertiesToFilters(
+ properties: QueryState['include']['properties']
+): PropertyFilter[] {
+ if (!properties?.length) return [];
+ const byPropId = new Map<string, PropertyFilter>();
+ for (const p of properties) {
+ let filter = byPropId.get(p.propertyId);
+ if (!filter) {
+ filter = { property_definition_id: p.propertyId };
+ byPropId.set(p.propertyId, filter);
+ }
+ if (p.type === 'select') {
+ filter.option_ids = [...(filter.option_ids ?? []), p.value];
+ } else {
+ filter.entity_ids = [...(filter.entity_ids ?? []), p.value];
+ }
+ }
+ return [...byPropId.values()];
+}
+
function filterDataToQueryFilters(data: QueryState): EntityFilters {
const filters: EntityFilters = {};
const { include } = data;
@@ -133,6 +159,12 @@ function filterDataToQueryFilters(data: QueryState): EntityFilters {
};
}
+ // Property filters (status, priority, assignees, custom)
+ const propertyFilters = includePropertiesToFilters(include.properties);
+ if (propertyFilters.length) {
+ filters.property_filters = propertyFilters;
+ }
+
return filters;
}
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx
index e1e6d0e25c..b697ed4db8 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx
@@ -4,6 +4,8 @@ import { UserIcon } from '@core/component/UserIcon';
import { useQuickAccess } from '@core/context/quickAccess';
import { useUserId } from '@core/context/user';
import { EntityIcon as EntityIconWithAvatar } from '@entity/extractors/entity-icon';
+import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';
+import { PROPERTY_OPTION_IDS } from '@property/constants';
import { type Accessor, createMemo, type JSX } from 'solid-js';
import { useInboxPicker } from '../inbox-picker';
import type { SearchableOption } from '../searchable-multi-select';
@@ -65,6 +67,61 @@ const CALL_STATUS_LABELS: Record<CallStatus, string> = {
UNATTENDED: 'Unattended',
};
+const optionIcon = (optionId: string) => () => (
+ <PropertyValueIcon optionId={optionId} class="size-3.5" />
+);
+
+const TASK_STATUS_OPTIONS: SearchableOption[] = [
+ {
+ id: PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,
+ label: 'Not Started',
+ icon: optionIcon(PROPERTY_OPTION_IDS.STATUS.NOT_STARTED),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
+ label: 'In Progress',
+ icon: optionIcon(PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.STATUS.IN_REVIEW,
+ label: 'In Review',
+ icon: optionIcon(PROPERTY_OPTION_IDS.STATUS.IN_REVIEW),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.STATUS.COMPLETED,
+ label: 'Completed',
+ icon: optionIcon(PROPERTY_OPTION_IDS.STATUS.COMPLETED),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.STATUS.CANCELED,
+ label: 'Canceled',
+ icon: optionIcon(PROPERTY_OPTION_IDS.STATUS.CANCELED),
+ },
+];
+
+const TASK_PRIORITY_OPTIONS: SearchableOption[] = [
+ {
+ id: PROPERTY_OPTION_IDS.PRIORITY.URGENT,
+ label: 'Urgent',
+ icon: optionIcon(PROPERTY_OPTION_IDS.PRIORITY.URGENT),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.PRIORITY.HIGH,
+ label: 'High',
+ icon: optionIcon(PROPERTY_OPTION_IDS.PRIORITY.HIGH),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.PRIORITY.MEDIUM,
+ label: 'Medium',
+ icon: optionIcon(PROPERTY_OPTION_IDS.PRIORITY.MEDIUM),
+ },
+ {
+ id: PROPERTY_OPTION_IDS.PRIORITY.LOW,
+ label: 'Low',
+ icon: optionIcon(PROPERTY_OPTION_IDS.PRIORITY.LOW),
+ },
+];
+
export type FacetOption = {
id: string;
label: string;
@@ -341,6 +398,46 @@ export function useSearchFacets(
controller.setCallStatus(id === 'all' ? undefined : (id as CallStatus)),
});
+ const taskStatus = multiFacet({
+ id: 'task-status',
+ label: 'Status',
+ neutralLabel: 'Any status',
+ placeholder: 'Filter by status...',
+ options: () => TASK_STATUS_OPTIONS,
+ activeIds: controller.taskStatus,
+ onChange: controller.setTaskStatus,
+ });
+
+ const taskPriority = multiFacet({
+ id: 'task-priority',
+ label: 'Priority',
+ neutralLabel: 'Any priority',
+ placeholder: 'Filter by priority...',
+ options: () => TASK_PRIORITY_OPTIONS,
+ activeIds: controller.taskPriority,
+ onChange: controller.setTaskPriority,
+ });
+
+ const taskAssignee = multiFacet({
+ id: 'task-assignee',
+ label: 'Assignee',
+ neutralLabel: 'Anyone',
+ placeholder: 'Search assignees...',
+ options: personOptions,
+ activeIds: controller.taskAssignees,
+ onChange: controller.setTaskAssignees,
+ });
+
+ const taskCreatedBy = multiFacet({
+ id: 'task-created-by',
+ label: 'Created by',
+ neutralLabel: 'Anyone',
+ placeholder: 'Search creators...',
+ options: personOptions,
+ activeIds: controller.taskCreatedBy,
+ onChange: controller.setTaskCreatedBy,
+ });
+
return createMemo(() => {
switch (controller.type()) {
case 'email':
@@ -351,6 +448,8 @@ export function useSearchFacets(
return [type, channelIn, channelFrom];
case 'calls':
return [type, callIn, callFrom, callStatus];
+ case 'task':
+ return [type, taskStatus, taskPriority, taskAssignee, taskCreatedBy];
default:
return [type];
}
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts
index ab789243ab..e599755fe3 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts
@@ -8,8 +8,10 @@ import {
type CallStatus,
callStatusFromAttended,
type FieldFilters,
+ type PropertyFilter,
} from '@app/component/next-soup/filters/filter-store/types';
import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { batch, createMemo } from 'solid-js';
export type SearchIndexId =
@@ -45,6 +47,12 @@ export type SearchFiltersSections = {
email: { importance: boolean | undefined; inboxIds: string[] | undefined };
channels: { in: string[]; from: string[] };
calls: { in: string[]; from: string[]; status: CallStatus | undefined };
+ task: {
+ status: string[];
+ priority: string[];
+ assignees: string[];
+ createdBy: string[];
+ };
};
export type SearchFiltersState = SearchFiltersSections & {
@@ -55,6 +63,7 @@ export const DEFAULT_SECTIONS: SearchFiltersSections = {
email: { importance: undefined, inboxIds: undefined },
channels: { in: [], from: [] },
calls: { in: [], from: [], status: undefined },
+ task: { status: [], priority: [], assignees: [], createdBy: [] },
};
/**
@@ -97,6 +106,28 @@ export function compileSearchQuery(state: SearchFiltersState): Query {
if (state.calls.status !== undefined) {
include.callStatus = state.calls.status;
}
+ } else if (state.type === 'task') {
+ const properties: PropertyFilter[] = [
+ ...state.task.status.map((value) => ({
+ propertyId: SYSTEM_PROPERTY_IDS.STATUS,
+ type: 'select' as const,
+ value,
+ })),
+ ...state.task.priority.map((value) => ({
+ propertyId: SYSTEM_PROPERTY_IDS.PRIORITY,
+ type: 'select' as const,
+ value,
+ })),
+ ...state.task.assignees.map((value) => ({
+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ type: 'entity' as const,
+ value,
+ })),
+ ];
+ if (properties.length) include.properties = properties;
+ if (state.task.createdBy.length) {
+ include.documentOwnerId = state.task.createdBy;
+ }
}
return { include, exclude };
@@ -135,10 +166,29 @@ export function createSearchFiltersController() {
const callStatus = () =>
include().callStatus ?? callStatusFromAttended(include().callAttended);
+ const taskProperty = (propertyId: string) =>
+ (include().properties ?? [])
+ .filter((p) => p.propertyId === propertyId)
+ .map((p) => p.value);
+ const taskStatus = createMemo(() => taskProperty(SYSTEM_PROPERTY_IDS.STATUS));
+ const taskPriority = createMemo(() =>
+ taskProperty(SYSTEM_PROPERTY_IDS.PRIORITY)
+ );
+ const taskAssignees = createMemo(() =>
+ taskProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES)
+ );
+ const taskCreatedBy = createMemo(() => withoutNil(include().documentOwnerId));
+
const currentSections = (): SearchFiltersSections => ({
email: { importance: emailImportance(), inboxIds: emailInbox() },
channels: { in: channelIn(), from: channelFrom() },
calls: { in: callIn(), from: callFrom(), status: callStatus() },
+ task: {
+ status: taskStatus(),
+ priority: taskPriority(),
+ assignees: taskAssignees(),
+ createdBy: taskCreatedBy(),
+ },
});
// Per-index values are remembered for the lifetime of the view: switching
@@ -173,6 +223,16 @@ export function createSearchFiltersController() {
...stash,
calls: { in: callIn(), from: callFrom(), status: callStatus() },
};
+ } else if (current === 'task') {
+ stash = {
+ ...stash,
+ task: {
+ status: taskStatus(),
+ priority: taskPriority(),
+ assignees: taskAssignees(),
+ createdBy: taskCreatedBy(),
+ },
+ };
}
apply({ type: next, ...stash });
@@ -208,6 +268,46 @@ export function createSearchFiltersController() {
callStatus,
setCallStatus: (status: CallStatus | undefined) =>
applySections({ calls: { in: callIn(), from: callFrom(), status } }),
+ taskStatus,
+ setTaskStatus: (ids: string[]) =>
+ applySections({
+ task: {
+ status: ids,
+ priority: taskPriority(),
+ assignees: taskAssignees(),
+ createdBy: taskCreatedBy(),
+ },
+ }),
+ taskPriority,
+ setTaskPriority: (ids: string[]) =>
+ applySections({
+ task: {
+ status: taskStatus(),
+ priority: ids,
+ assignees: taskAssignees(),
+ createdBy: taskCreatedBy(),
+ },
+ }),
+ taskAssignees,
+ setTaskAssignees: (ids: string[]) =>
+ applySections({
+ task: {
+ status: taskStatus(),
+ priority: taskPriority(),
+ assignees: ids,
+ createdBy: taskCreatedBy(),
+ },
+ }),
+ taskCreatedBy,
+ setTaskCreatedBy: (ids: string[]) =>
+ applySections({
+ task: {
+ status: taskStatus(),
+ priority: taskPriority(),
+ assignees: taskAssignees(),
+ createdBy: ids,
+ },
+ }),
};
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index e8109447d1..7e489b6f28 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -13,7 +13,7 @@ use chrono::{DateTime, Utc};
use models_opensearch::{OpenSearchEntityType, SearchEntityType};
use opensearch_query_builder::{
BoolQueryBuilder, HasChildQuery, InnerHits, MatchPhrasePrefixQuery, MatchPhraseQuery,
- QueryType, ToOpenSearchJson,
+ NestedQuery, QueryType, ToOpenSearchJson,
};
/// Relation names for the join field. Kept in sync with the upsert path
@@ -53,6 +53,22 @@ pub enum DocumentSearchMode {
NameContent,
}
+/// Nested path holding denormalized entity properties on the parent doc.
+const PROPERTIES_PATH: &str = "properties";
+
+/// A property-equality filter applied against the indexed `properties` nested
+/// field. Matches parents that have a nested entry whose `definition_id`
+/// equals `definition_id` and whose `values` contains any of `values`.
+/// Empty `values` means "no constraint" and is dropped before querying.
+#[derive(Debug, Clone)]
+pub struct PropertyFilterArg {
+ /// The property definition id to match on.
+ pub definition_id: String,
+ /// Candidate values (OR'd). Select-option UUIDs and entity-ref ids both
+ /// live in the indexed `values` keyword array.
+ pub values: Vec<String>,
+}
+
#[derive(Clone)]
pub(crate) struct DocumentSearchConfig;
@@ -66,6 +82,7 @@ pub(crate) struct DocumentQueryBuilder {
inner: SearchQueryBuilder<DocumentSearchConfig>,
sub_types: Vec<String>,
mode: DocumentSearchMode,
+ property_filters: Vec<PropertyFilterArg>,
}
impl DocumentQueryBuilder {
@@ -74,6 +91,7 @@ impl DocumentQueryBuilder {
inner: SearchQueryBuilder::new(terms),
sub_types: Vec::new(),
mode: DocumentSearchMode::default(),
+ property_filters: Vec::new(),
}
}
@@ -98,6 +116,11 @@ impl DocumentQueryBuilder {
self
}
+ pub fn property_filters(mut self, property_filters: Vec<PropertyFilterArg>) -> Self {
+ self.property_filters = property_filters;
+ self
+ }
+
/// Parent/child join query: one `has_child` clause per term, ANDed
/// inside `bool.must`. Parent metadata filters (owner, ids,
/// sub_type) sit on `bool.filter` directly because they live on
@@ -132,6 +155,16 @@ impl DocumentQueryBuilder {
bool_query.filter(QueryType::terms("sub_type", self.sub_types.clone()));
}
+ // Property filters: one nested clause per filter, ANDed via bool.filter.
+ // Each matches a `properties` entry whose definition_id and value line
+ // up within the same nested object. On bool.filter, so they constrain
+ // both name and content matches.
+ for filter in &self.property_filters {
+ if let Some(nested) = build_property_filter(filter) {
+ bool_query.filter(nested);
+ }
+ }
+
// Match clause(s) per mode: the parent `document_name` (Name), child
// chunk `content` via has_child (Content), or either (NameContent).
let include_name = matches!(
@@ -215,6 +248,32 @@ impl DocumentQueryBuilder {
}
}
+/// Build a `nested` query over `properties` for one property filter:
+/// a parent matches when it has a nested entry with `definition_id` equal to
+/// the filter's id AND `values` containing any of the filter's values.
+/// Returns `None` when the filter carries no values.
+fn build_property_filter<'a>(filter: &PropertyFilterArg) -> Option<QueryType<'a>> {
+ if filter.values.is_empty() {
+ return None;
+ }
+ let mut inner = BoolQueryBuilder::new();
+ inner.filter(QueryType::term(
+ format!("{PROPERTIES_PATH}.definition_id"),
+ filter.definition_id.clone(),
+ ));
+ inner.filter(QueryType::terms(
+ format!("{PROPERTIES_PATH}.values"),
+ filter.values.clone(),
+ ));
+ // ignore_unmapped: the unified query spans indices that don't map
+ // `properties` as nested; there the clause is a no-op rather than an error.
+ Some(
+ NestedQuery::new(PROPERTIES_PATH, inner.build().into())
+ .ignore_unmapped(true)
+ .into(),
+ )
+}
+
/// Highlight config attached to each `has_child` inner_hits block.
/// Matches the top-level documents highlight (plain highlighter,
/// `<macro_em>` tags, single fragment) so chunk hits come back with
@@ -302,6 +361,7 @@ pub struct DocumentSearchArgs {
pub ids_only: bool,
pub sub_types: Vec<String>,
pub mode: DocumentSearchMode,
+ pub property_filters: Vec<PropertyFilterArg>,
}
impl From<DocumentSearchArgs> for DocumentQueryBuilder {
@@ -316,6 +376,7 @@ impl From<DocumentSearchArgs> for DocumentQueryBuilder {
.ids_only(args.ids_only)
.sub_types(args.sub_types)
.mode(args.mode)
+ .property_filters(args.property_filters)
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
index 67312c4fed..7a110f4e3d 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
@@ -222,6 +222,72 @@ fn test_build_bool_query_name_content_mode_matches_either() -> anyhow::Result<()
Ok(())
}
+#[test]
+fn test_build_bool_query_property_filters_emit_nested() -> anyhow::Result<()> {
+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])
+ .match_type("partial")
+ .user_id("alice")
+ .property_filters(vec![
+ PropertyFilterArg {
+ definition_id: "00000001-0000-0000-0000-000000000002".to_string(),
+ values: vec![
+ "00000001-0000-0000-0002-000000000001".to_string(),
+ "00000001-0000-0000-0002-000000000004".to_string(),
+ ],
+ },
+ PropertyFilterArg {
+ definition_id: "00000001-0000-0000-0000-000000000001".to_string(),
+ values: vec!["macro|[email protected]".to_string()],
+ },
+ ]);
+
+ let json = builder.build_bool_query()?.build().to_json();
+ let filter = json["bool"]["filter"].as_array().expect("filter array");
+
+ let nested: Vec<&serde_json::Value> = filter
+ .iter()
+ .filter(|f| f.get("nested").is_some())
+ .collect();
+ assert_eq!(nested.len(), 2, "one nested clause per filter: {filter:?}");
+
+ let status = &nested[0]["nested"];
+ assert_eq!(status["path"], "properties");
+ assert_eq!(status["ignore_unmapped"], true);
+ let status_inner = status["query"]["bool"]["filter"]
+ .as_array()
+ .expect("nested bool filter");
+ assert!(status_inner.contains(&serde_json::json!({
+ "term": {"properties.definition_id": "00000001-0000-0000-0000-000000000002"}
+ })));
+ assert!(status_inner.contains(&serde_json::json!({
+ "terms": {"properties.values": [
+ "00000001-0000-0000-0002-000000000001",
+ "00000001-0000-0000-0002-000000000004"
+ ]}
+ })));
+
+ Ok(())
+}
+
+#[test]
+fn test_build_bool_query_property_filter_empty_values_skipped() -> anyhow::Result<()> {
+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])
+ .match_type("partial")
+ .user_id("alice")
+ .property_filters(vec![PropertyFilterArg {
+ definition_id: "00000001-0000-0000-0000-000000000002".to_string(),
+ values: vec![],
+ }]);
+
+ let json = builder.build_bool_query()?.build().to_json();
+ let filter = json["bool"]["filter"].as_array().expect("filter array");
+ assert!(
+ !filter.iter().any(|f| f.get("nested").is_some()),
+ "empty-values filter should emit no nested clause: {filter:?}"
+ );
+ Ok(())
+}
+
#[test]
fn document_index_deserializes_parent_shape() {
// Parent docs carry only parent-level metadata in `_source`; the
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index ea867f3d28..4cbee1ab8d 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -15,7 +15,7 @@ use crate::{
chats::{ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig},
documents::{
DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,
- DocumentSearchMode,
+ DocumentSearchMode, PropertyFilterArg,
},
emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},
model::{
@@ -79,6 +79,7 @@ impl From<UnifiedSearchArgs> for DocumentSearchArgs {
document_ids: args.document_search_args.document_ids,
sub_types: args.document_search_args.sub_types,
mode: args.document_search_args.mode,
+ property_filters: args.document_search_args.property_filters,
}
}
}
@@ -174,6 +175,7 @@ pub struct UnifiedDocumentSearchArgs {
pub ids_only: bool,
pub sub_types: Vec<String>,
pub mode: DocumentSearchMode,
+ pub property_filters: Vec<PropertyFilterArg>,
}
#[derive(Debug, Default, Clone)]
diff --git a/rust/cloud-storage/opensearch_query_builder/src/lib.rs b/rust/cloud-storage/opensearch_query_builder/src/lib.rs
index c3c22d73d5..2d1c0a7415 100644
--- a/rust/cloud-storage/opensearch_query_builder/src/lib.rs
+++ b/rust/cloud-storage/opensearch_query_builder/src/lib.rs
@@ -14,7 +14,7 @@ mod util;
pub use query::{
BoolQuery, BoolQueryBuilder, BoostMode, DecayFunction, FieldValueFactor, FunctionScoreQuery,
FunctionScoreQueryBuilder, HasChildQuery, InnerHits, MatchPhrasePrefixQuery, MatchPhraseQuery,
- MatchQuery, QueryType, RandomScore, RangeQuery, RangeQueryBuilder, RegexpQuery,
+ MatchQuery, NestedQuery, QueryType, RandomScore, RangeQuery, RangeQueryBuilder, RegexpQuery,
RegexpQueryFlags, ScoreFunction, ScoreFunctionType, ScoreMode, ScriptScore,
SimpleQueryStringQuery, TermQuery, TermsQuery, WildcardQuery,
};
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query.rs b/rust/cloud-storage/opensearch_query_builder/src/query.rs
index 1fb6b50d36..a8e2bbb04f 100644
--- a/rust/cloud-storage/opensearch_query_builder/src/query.rs
+++ b/rust/cloud-storage/opensearch_query_builder/src/query.rs
@@ -8,6 +8,7 @@ mod has_child;
mod match_phrase;
mod match_phrase_prefix;
mod match_query;
+mod nested;
mod range;
mod regexp;
mod simple_query_string;
@@ -25,6 +26,7 @@ pub use has_child::{HasChildQuery, InnerHits};
pub use match_phrase::MatchPhraseQuery;
pub use match_phrase_prefix::MatchPhrasePrefixQuery;
pub use match_query::MatchQuery;
+pub use nested::NestedQuery;
pub use range::{RangeQuery, RangeQueryBuilder};
pub use regexp::{RegexpQuery, RegexpQueryFlags};
use serde_json::Value;
@@ -61,6 +63,8 @@ pub enum QueryType<'a> {
SimpleQueryString(SimpleQueryStringQuery<'a>),
/// has_child join query (returns parents whose children match)
HasChild(HasChildQuery<'a>),
+ /// nested query (returns parents whose nested objects match)
+ Nested(NestedQuery<'a>),
}
impl<'a> ToOpenSearchJson for QueryType<'a> {
@@ -78,6 +82,7 @@ impl<'a> ToOpenSearchJson for QueryType<'a> {
QueryType::Regexp(regexp_query) => regexp_query.to_json(),
QueryType::SimpleQueryString(simple_query_string) => simple_query_string.to_json(),
QueryType::HasChild(has_child) => has_child.to_json(),
+ QueryType::Nested(nested) => nested.to_json(),
}
}
}
@@ -165,6 +170,7 @@ impl<'a> QueryType<'a> {
QueryType::WildCard(wildcard) => QueryType::WildCard(wildcard.to_owned()),
QueryType::SimpleQueryString(sqs) => QueryType::SimpleQueryString(sqs.to_owned()),
QueryType::HasChild(has_child) => QueryType::HasChild(has_child.to_owned()),
+ QueryType::Nested(nested) => QueryType::Nested(nested.to_owned()),
}
}
}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/nested.rs b/rust/cloud-storage/opensearch_query_builder/src/query/nested.rs
new file mode 100644
index 0000000000..597293b1e2
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/nested.rs
@@ -0,0 +1,72 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// `nested` query. Returns documents whose nested objects under `path`
+/// match `query` within a single nested entry.
+///
+/// `ignore_unmapped` is set so the query is a no-op (rather than an error)
+/// on indices in a multi-index search that don't map `path` as nested.
+#[derive(Debug, Clone, Serialize)]
+pub struct NestedQuery<'a> {
+ /// Path to the nested field.
+ #[serde(borrow)]
+ pub path: Cow<'a, str>,
+ /// Query to run against each nested object. A parent matches if any one
+ /// of its nested objects matches this query.
+ pub query: Box<QueryType<'a>>,
+ /// If true, suppress errors when `path` is not mapped as nested in the
+ /// target index. Useful for unified queries that span heterogeneous
+ /// indices, only some of which map the nested field.
+ pub ignore_unmapped: Option<bool>,
+}
+
+impl<'a> NestedQuery<'a> {
+ /// Create a new nested query against `path` running `query`.
+ pub fn new(path: impl Into<Cow<'a, str>>, query: QueryType<'a>) -> Self {
+ Self {
+ path: path.into(),
+ query: Box::new(query),
+ ignore_unmapped: None,
+ }
+ }
+
+ /// Ignore mapping errors when `path` is not mapped as nested on the
+ /// target index.
+ pub fn ignore_unmapped(mut self, ignore: bool) -> Self {
+ self.ignore_unmapped = Some(ignore);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime.
+ pub fn to_owned(&self) -> NestedQuery<'static> {
+ NestedQuery {
+ path: Cow::Owned(self.path.to_string()),
+ query: Box::new((*self.query).to_owned()),
+ ignore_unmapped: self.ignore_unmapped,
+ }
+ }
+}
+
+impl<'a> From<NestedQuery<'a>> for QueryType<'a> {
+ fn from(q: NestedQuery<'a>) -> Self {
+ QueryType::Nested(q)
+ }
+}
+
+impl<'a> ToOpenSearchJson for NestedQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut inner = Map::new();
+ inner.insert("path".to_string(), Value::String(self.path.to_string()));
+ inner.insert("query".to_string(), self.query.to_json());
+ if let Some(ignore) = self.ignore_unmapped {
+ inner.insert("ignore_unmapped".to_string(), Value::Bool(ignore));
+ }
+ let mut outer = Map::new();
+ outer.insert("nested".to_string(), Value::Object(inner));
+ Value::Object(outer)
+ }
+}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
index 54839674fb..2affa74b37 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
@@ -21,7 +21,7 @@ use models_search::{
unified::{SimpleUnifiedSearchResponse, UnifiedSearchRequest},
};
use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};
-use opensearch_client::search::documents::DocumentSearchMode;
+use opensearch_client::search::documents::{DocumentSearchMode, PropertyFilterArg};
use opensearch_client::search::model::SearchHit;
use opensearch_client::search::unified::UnifiedSearchArgs;
@@ -108,6 +108,33 @@ fn enforce_term_limits(terms: Vec<String>) -> Result<Vec<String>, SearchError> {
.collect())
}
+/// Convert request property filters into OpenSearch property-filter args.
+///
+/// `entity_type` is dropped: the indexed `properties` field carries only
+/// `definition_id` + `values`, and definition ids are globally unique, so the
+/// entity type adds nothing to the query. Select-option UUIDs and entity-ref
+/// ids both match against `values`. Filters with no values are skipped.
+fn to_property_filter_args(filters: &[item_filters::PropertyFilter]) -> Vec<PropertyFilterArg> {
+ filters
+ .iter()
+ .filter_map(|f| {
+ let values: Vec<String> = f
+ .option_ids
+ .iter()
+ .chain(f.entity_ids.iter())
+ .cloned()
+ .collect();
+ if values.is_empty() {
+ return None;
+ }
+ Some(PropertyFilterArg {
+ definition_id: f.property_definition_id.clone(),
+ values,
+ })
+ })
+ .collect()
+}
+
/// Creates a unified search request and performs the search
/// by calling individual simple search endpoints for each entity type
#[tracing::instrument(skip(ctx, user_context, query_params), fields(user_id = %user_context.user_id), err)]
@@ -169,6 +196,11 @@ pub(in crate::api::search) async fn perform_unified_search(
let crm_company_filters = req.filters.crm_company_filters.clone();
let should_include_crm = crm_access.is_some();
+ // Property filters live at the top level of the request and only apply to
+ // the OpenSearch documents index, so capture them before the conversion
+ // (which drops them) and attach them to the document search args below.
+ let property_filter_args = to_property_filter_args(&req.filters.property_filters);
+
let search_filters = SearchEntityFilters::from(req.filters);
let channel_filters = search_filters.channel_filters;
let email_filters = search_filters.email_filters;
@@ -242,6 +274,7 @@ pub(in crate::api::search) async fn perform_unified_search(
// call records are join-shape, where each term becomes a separate
// has_child clause ANDed via bool.must.
filter_document_response.terms = search_terms.clone();
+ filter_document_response.property_filters = property_filter_args;
filter_channel_response.terms = search_terms.clone();
filter_chat_response.terms = search_terms.clone();
filter_email_response.terms = email_terms.clone();