Skip to content

SearchIndex

API reference

synapseclient.models.SearchIndex dataclass

Bases: SearchIndexSynchronousProtocol, AccessControllable, DeleteMixin, GetMixin

A SearchIndex is a Synapse entity whose content is defined by a Synapse SQL query (defining_sql). An OpenSearch index is built from the query results, supporting full-text search, faceted search, and autocomplete.

The defining_sql must reference exactly one table-like entity. Multi-entity JOIN/UNION queries are not supported. Optionally, a search_configuration_id may be supplied to control the analyzer/synonym settings used when building the index. If not specified, the configuration is resolved by walking up the entity hierarchy.

REST API model: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/table/SearchIndex.html

ATTRIBUTE DESCRIPTION
id

The unique immutable ID for this entity.

TYPE: Optional[str]

name

The name of this entity.

TYPE: Optional[str]

description

The description of this entity.

TYPE: Optional[str]

etag

Synapse OCC etag.

TYPE: Optional[str]

created_on

Date this entity was created.

TYPE: Optional[str]

modified_on

Date this entity was last modified.

TYPE: Optional[str]

created_by

The ID of the user that created this entity.

TYPE: Optional[str]

modified_by

The ID of the user that last modified this entity.

TYPE: Optional[str]

parent_id

The ID of the parent entity.

TYPE: Optional[str]

defining_sql

The Synapse SQL statement that defines which columns and rows are indexed.

TYPE: Optional[str]

search_configuration_id

ID of the SearchConfiguration to apply when building this index. Optional.

TYPE: Optional[str]

annotations

Additional metadata associated with the entity.

TYPE: Optional[Dict[str, Union[List[str], List[bool], List[float], List[int], List[date], List[datetime]]]]

activity

Provenance for this entity.

TYPE: Optional[Activity]

Create a new SearchIndex.

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex

syn = Synapse()
syn.login()

index = SearchIndex(
    name="My Search Index",
    parent_id="syn12345",
    # syn67890 must be a table or a view; multi-entity JOINs are not supported
    defining_sql="SELECT * FROM syn67890",
)
index = index.store()
print(f"Created SearchIndex: {index.id}")
Source code in synapseclient/models/search_index.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
@dataclass
@async_to_sync
class SearchIndex(
    SearchIndexSynchronousProtocol,
    AccessControllable,
    DeleteMixin,
    GetMixin,
):
    """
    A SearchIndex is a Synapse entity whose content is defined by a Synapse SQL
    query (`defining_sql`). An OpenSearch index is built from the query results,
    supporting full-text search, faceted search, and autocomplete.

    The `defining_sql` must reference exactly one table-like entity. Multi-entity
    JOIN/UNION queries are not supported. Optionally, a `search_configuration_id`
    may be supplied to control the analyzer/synonym settings used when building
    the index. If not specified, the configuration is resolved by walking up
    the entity hierarchy.

    REST API model: <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/table/SearchIndex.html>

    Attributes:
        id: The unique immutable ID for this entity.
        name: The name of this entity.
        description: The description of this entity.
        etag: Synapse OCC etag.
        created_on: Date this entity was created.
        modified_on: Date this entity was last modified.
        created_by: The ID of the user that created this entity.
        modified_by: The ID of the user that last modified this entity.
        parent_id: The ID of the parent entity.
        defining_sql: The Synapse SQL statement that defines which columns and
            rows are indexed.
        search_configuration_id: ID of the SearchConfiguration to apply when
            building this index. Optional.
        annotations: Additional metadata associated with the entity.
        activity: Provenance for this entity.

    Example: Create a new SearchIndex.
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        syn = Synapse()
        syn.login()

        index = SearchIndex(
            name="My Search Index",
            parent_id="syn12345",
            # syn67890 must be a table or a view; multi-entity JOINs are not supported
            defining_sql="SELECT * FROM syn67890",
        )
        index = index.store()
        print(f"Created SearchIndex: {index.id}")
        ```
    """

    id: Optional[str] = None
    """The unique immutable ID for this entity. A new ID will be generated for
    new Entities. Once issued, this ID is guaranteed to never change or be
    re-issued."""

    name: Optional[str] = None
    """The name of this entity. Must be 256 characters or less. Names may only
    contain: letters, numbers, spaces, underscores, hyphens, periods, plus
    signs, apostrophes, and parentheses."""

    description: Optional[str] = None
    """The description of this entity. Must be 1000 characters or less."""

    etag: Optional[str] = field(default=None, compare=False)
    """Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle
    concurrent updates. Since the E-Tag changes every time an entity is
    updated it is used to detect when a client's current representation of an
    entity is out-of-date."""

    created_on: Optional[str] = field(default=None, compare=False)
    """The date this entity was created."""

    modified_on: Optional[str] = field(default=None, compare=False)
    """The date this entity was last modified."""

    created_by: Optional[str] = field(default=None, compare=False)
    """The ID of the user that created this entity."""

    modified_by: Optional[str] = field(default=None, compare=False)
    """The ID of the user that last modified this entity."""

    parent_id: Optional[str] = None
    """The ID of the Entity that is the parent of this Entity."""

    defining_sql: Optional[str] = None
    """The Synapse SQL statement that defines which columns and rows are indexed.
    Must reference exactly one entity."""

    search_configuration_id: Optional[str] = None
    """The ID of the SearchConfiguration to apply when building this search
    index. If not provided, the system will check for a search configuration
    binding on the parent project/folder hierarchy, or use platform defaults."""

    _last_persistent_instance: Optional["SearchIndex"] = field(
        default=None, repr=False, compare=False
    )
    """The last persistent instance of this object. This is used to determine if the
    object has been changed and needs to be updated in Synapse."""

    annotations: Optional[
        Dict[
            str,
            Union[
                List[str],
                List[bool],
                List[float],
                List[int],
                List[date],
                List[datetime],
            ],
        ]
    ] = field(default_factory=dict, compare=False)

    activity: Optional[Activity] = field(default=None, compare=False)

    @property
    def has_changed(self) -> bool:
        """Checks if the object has changed since the last persistent instance."""
        return self._last_persistent_instance != self

    def _set_last_persistent_instance(self) -> None:
        """Stash the last time this object interacted with Synapse."""
        del self._last_persistent_instance
        self._last_persistent_instance = replace(self)
        self._last_persistent_instance.activity = (
            replace(self.activity) if self.activity and self.activity.id else None
        )
        self._last_persistent_instance.annotations = (
            deepcopy(self.annotations) if self.annotations else {}
        )

    def fill_from_dict(
        self, entity: Dict[str, Any], set_annotations: bool = True
    ) -> "SearchIndex":
        """Populate this dataclass from a Synapse REST API entity dict."""
        self.id = entity.get("id", None)
        self.name = entity.get("name", None)
        self.description = entity.get("description", None)
        self.parent_id = entity.get("parentId", None)
        self.etag = entity.get("etag", None)
        self.created_on = entity.get("createdOn", None)
        self.created_by = entity.get("createdBy", None)
        self.modified_on = entity.get("modifiedOn", None)
        self.modified_by = entity.get("modifiedBy", None)
        self.defining_sql = entity.get("definingSQL", None)
        self.search_configuration_id = entity.get("searchConfigurationId", None)

        if set_annotations:
            self.annotations = entity.get("annotations", {})

        return self

    def to_synapse_request(self) -> Dict[str, Any]:
        """Convert this dataclass into the entity body expected by the Synapse
        REST API."""
        entity = {
            "concreteType": concrete_types.SEARCH_INDEX_ENTITY,
            "name": self.name,
            "description": self.description,
            "id": self.id,
            "etag": self.etag,
            "createdOn": self.created_on,
            "modifiedOn": self.modified_on,
            "createdBy": self.created_by,
            "modifiedBy": self.modified_by,
            "parentId": self.parent_id,
            "definingSQL": self.defining_sql,
            "searchConfigurationId": self.search_configuration_id,
        }
        delete_none_keys(entity)
        return entity

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Store: {self.name}"
    )
    async def store_async(
        self,
        dry_run: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Self":
        """Asynchronously store the SearchIndex entity. Creates a new SearchIndex
        if `id` is not set, or updates the existing one otherwise. `defining_sql`
        must be set before calling this.

        Arguments:
            dry_run: If True, will not actually store the SearchIndex but will log
                to the console what would be created or updated.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            Itself.

        Raises:
            ValueError: If `defining_sql` is not set.

        Example: Create a new SearchIndex.
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex

            async def main():
                syn = Synapse()
                syn.login()

                index = SearchIndex(
                    name="My Search Index",
                    parent_id="syn12345",
                    # syn67890 must be a table or a view;
                    defining_sql="SELECT * FROM syn67890",
                )
                index = await index.store_async()
                print(f"Created SearchIndex: {index.id}")

            asyncio.run(main())
            ```
        """
        if not self.defining_sql:
            raise ValueError(
                "The defining_sql attribute must be set for a SearchIndex."
            )
        client = Synapse.get_client(synapse_client=synapse_client)

        if (
            (not self._last_persistent_instance)
            and (
                existing_id := await get_id(
                    entity=self, failure_strategy=None, synapse_client=synapse_client
                )
            )
            and (
                existing_index := await SearchIndex(id=existing_id).get_async(
                    synapse_client=synapse_client
                )
            )
        ):
            merge_dataclass_entities(
                source=existing_index, destination=self, logger=client.logger
            )

        if dry_run:
            client.logger.info(
                f"[{self.id}:{self.name}]: Dry run enabled. No changes will be made."
            )
            if self.has_changed:
                log_dataclass_diff(
                    logger=client.logger,
                    prefix=f"[{self.id}:{self.name}]: ",
                    obj1=self._last_persistent_instance or SearchIndex(),
                    obj2=self,
                    fields_to_ignore=["_last_persistent_instance"],
                )
            return self

        if self.has_changed:
            entity = await store_entity(
                resource=self,
                entity=self.to_synapse_request(),
                synapse_client=synapse_client,
            )
            self.fill_from_dict(entity=entity, set_annotations=False)

        re_read_required = await store_entity_components(
            root_resource=self,
            failure_strategy=FailureStrategy.RAISE_EXCEPTION,
            synapse_client=synapse_client,
        )
        if re_read_required:
            await self.get_async(synapse_client=synapse_client)
        self._set_last_persistent_instance()

        return self

    async def get_async(
        self,
        include_activity: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Self":
        """Asynchronously fetch the SearchIndex metadata. Either `id`, or `name`
        and `parent_id`, must be set before calling this.

        Arguments:
            include_activity: If True, will include the provenance activity on
                the returned SearchIndex.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            Itself, populated from the Synapse response.

        Example: Get a SearchIndex by ID.
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex

            async def main():
                syn = Synapse()
                await syn.login_async()

                index = await SearchIndex(id="syn12345").get_async()
                print(index.name, index.defining_sql)

            asyncio.run(main())
            ```
        """
        return await super().get_async(
            include_columns=False,
            include_activity=include_activity,
            synapse_client=synapse_client,
        )

    async def delete_async(self, *, synapse_client: Optional[Synapse] = None) -> None:
        """Asynchronously delete this SearchIndex from Synapse. `id` must be set
        before calling this.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Example: Delete a SearchIndex by ID.
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex

            async def main():
                syn = Synapse()
                await syn.login_async()

                await SearchIndex(id="syn12345").delete_async()

            asyncio.run(main())
            ```
        """
        await super().delete_async(synapse_client=synapse_client)

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Query: {self.id}"
    )
    async def query_async(
        self,
        search_query: "SearchQuery",
        response_parts: Optional[List["SearchQueryPart"]] = None,
        *,
        job_timeout: int = 600,
        synapse_client: Optional[Synapse] = None,
    ) -> "SearchIndexQuery":
        """Asynchronously query this search index. Unlike a SQL-backed Table, a
        SearchIndex is queried with the
        [OpenSearch Query DSL](https://docs.opensearch.org/latest/query-dsl/)
        carried by a [SearchQuery][synapseclient.models.SearchQuery] — not with
        Synapse SQL. See [Query][synapseclient.models.search_dsl.Query] for the
        supported clause kinds.

        Arguments:
            search_query: The OpenSearch
                [`_search`](https://docs.opensearch.org/latest/api-reference/search-apis/search/)
                body to execute against this index.
            response_parts: Additional response parts to request beyond the
                default hits, such as the total hit count or the select columns.
            job_timeout: The maximum amount of time to wait for the query job to
                complete before raising a `SynapseTimeoutError`.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            The completed [SearchIndexQuery][synapseclient.models.SearchIndexQuery], carrying the `hits` and any requested response parts.

        Raises:
            ValueError: If the `id` attribute has not been set.

        Example: Query an index for documents mentioning "alzheimer".
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
            from synapseclient.models.search_dsl import Query

            async def main():
                syn = Synapse()
                await syn.login_async()

                results = await SearchIndex(id="syn12345").query_async(
                    search_query=SearchQuery(
                        query=Query(match={"title": {"query": "alzheimer"}}),
                        size=10,
                    ),
                    response_parts=[SearchQueryPart.TOTAL_HITS],
                )
                print(results.total_hits)
                for hit in results.hits:
                    print(hit.row_id, hit.fields)

            asyncio.run(main())
            ```
        """
        from synapseclient.models.search_management import SearchIndexQuery

        if not self.id:
            raise ValueError("The id attribute must be set to query a SearchIndex.")
        return await SearchIndexQuery(
            search_index_id=self.id,
            search_query=search_query,
            response_parts=response_parts or [],
        ).send_job_and_wait_async(timeout=job_timeout, synapse_client=synapse_client)

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Autocomplete: {self.id}"
    )
    async def autocomplete_async(
        self,
        query: Query,
        source: Optional[SourceFilter] = None,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> List["SearchHit"]:
        """Run a synchronous autocomplete search against this index. The
        autocomplete endpoint allow lists only prefix-style queries
        ([`prefix`](https://docs.opensearch.org/latest/query-dsl/term/prefix/),
        [`match_phrase_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase-prefix/),
        or [`match_bool_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-bool-prefix/))
        and caps results at 8.

        Arguments:
            query: The top-level [OpenSearch Query DSL](https://docs.opensearch.org/latest/query-dsl/)
                clause -- see [Query][synapseclient.models.search_dsl.Query];
                restricted server-side to `prefix`, `match_phrase_prefix`, or
                `match_bool_prefix`.
            source: Optional [source filter](https://docs.opensearch.org/latest/search-plugins/searching-data/retrieve-specific-fields/)
                selecting which columns are returned on each hit.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            The matching SearchHits, capped at 8.

        Raises:
            ValueError: If the ``id`` attribute has not been set.

        Example: Autocomplete titles beginning with "alz".
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex
            from synapseclient.models.search_dsl import PrefixFieldOptions, Query

            async def main():
                syn = Synapse()
                await syn.login_async()

                index = SearchIndex(id="syn12345")
                hits = await index.autocomplete_async(
                    query=Query(
                        prefix={"title": PrefixFieldOptions(value="alz")}
                    ),
                )
                for hit in hits:
                    print(hit.row_id, hit.fields)

            asyncio.run(main())
            ```
        """
        from synapseclient.api import autocomplete_search
        from synapseclient.models.search_management import (
            SearchAutocompleteRequest,
            SearchHit,
        )

        if not self.id:
            raise ValueError("The id attribute must be set to call autocomplete.")
        request = SearchAutocompleteRequest(
            search_index_id=self.id,
            query=query,
            source=source,
        )
        response = await autocomplete_search(
            request.to_synapse_request(), synapse_client=synapse_client
        )
        return [SearchHit().fill_from_dict(h) for h in response.get("hits", []) or []]

Methods:

store_async async

store_async(dry_run: bool = False, *, synapse_client: Optional[Synapse] = None) -> Self

Asynchronously store the SearchIndex entity. Creates a new SearchIndex if id is not set, or updates the existing one otherwise. defining_sql must be set before calling this.

PARAMETER DESCRIPTION
dry_run

If True, will not actually store the SearchIndex but will log to the console what would be created or updated.

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Self

Itself.

RAISES DESCRIPTION
ValueError

If defining_sql is not set.

Create a new SearchIndex.

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndex

async def main():
    syn = Synapse()
    syn.login()

    index = SearchIndex(
        name="My Search Index",
        parent_id="syn12345",
        # syn67890 must be a table or a view;
        defining_sql="SELECT * FROM syn67890",
    )
    index = await index.store_async()
    print(f"Created SearchIndex: {index.id}")

asyncio.run(main())
Source code in synapseclient/models/search_index.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Store: {self.name}"
)
async def store_async(
    self,
    dry_run: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Asynchronously store the SearchIndex entity. Creates a new SearchIndex
    if `id` is not set, or updates the existing one otherwise. `defining_sql`
    must be set before calling this.

    Arguments:
        dry_run: If True, will not actually store the SearchIndex but will log
            to the console what would be created or updated.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        Itself.

    Raises:
        ValueError: If `defining_sql` is not set.

    Example: Create a new SearchIndex.
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        async def main():
            syn = Synapse()
            syn.login()

            index = SearchIndex(
                name="My Search Index",
                parent_id="syn12345",
                # syn67890 must be a table or a view;
                defining_sql="SELECT * FROM syn67890",
            )
            index = await index.store_async()
            print(f"Created SearchIndex: {index.id}")

        asyncio.run(main())
        ```
    """
    if not self.defining_sql:
        raise ValueError(
            "The defining_sql attribute must be set for a SearchIndex."
        )
    client = Synapse.get_client(synapse_client=synapse_client)

    if (
        (not self._last_persistent_instance)
        and (
            existing_id := await get_id(
                entity=self, failure_strategy=None, synapse_client=synapse_client
            )
        )
        and (
            existing_index := await SearchIndex(id=existing_id).get_async(
                synapse_client=synapse_client
            )
        )
    ):
        merge_dataclass_entities(
            source=existing_index, destination=self, logger=client.logger
        )

    if dry_run:
        client.logger.info(
            f"[{self.id}:{self.name}]: Dry run enabled. No changes will be made."
        )
        if self.has_changed:
            log_dataclass_diff(
                logger=client.logger,
                prefix=f"[{self.id}:{self.name}]: ",
                obj1=self._last_persistent_instance or SearchIndex(),
                obj2=self,
                fields_to_ignore=["_last_persistent_instance"],
            )
        return self

    if self.has_changed:
        entity = await store_entity(
            resource=self,
            entity=self.to_synapse_request(),
            synapse_client=synapse_client,
        )
        self.fill_from_dict(entity=entity, set_annotations=False)

    re_read_required = await store_entity_components(
        root_resource=self,
        failure_strategy=FailureStrategy.RAISE_EXCEPTION,
        synapse_client=synapse_client,
    )
    if re_read_required:
        await self.get_async(synapse_client=synapse_client)
    self._set_last_persistent_instance()

    return self

get_async async

get_async(include_activity: bool = False, *, synapse_client: Optional[Synapse] = None) -> Self

Asynchronously fetch the SearchIndex metadata. Either id, or name and parent_id, must be set before calling this.

PARAMETER DESCRIPTION
include_activity

If True, will include the provenance activity on the returned SearchIndex.

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Self

Itself, populated from the Synapse response.

Get a SearchIndex by ID.

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndex

async def main():
    syn = Synapse()
    await syn.login_async()

    index = await SearchIndex(id="syn12345").get_async()
    print(index.name, index.defining_sql)

asyncio.run(main())
Source code in synapseclient/models/search_index.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
async def get_async(
    self,
    include_activity: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Asynchronously fetch the SearchIndex metadata. Either `id`, or `name`
    and `parent_id`, must be set before calling this.

    Arguments:
        include_activity: If True, will include the provenance activity on
            the returned SearchIndex.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        Itself, populated from the Synapse response.

    Example: Get a SearchIndex by ID.
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        async def main():
            syn = Synapse()
            await syn.login_async()

            index = await SearchIndex(id="syn12345").get_async()
            print(index.name, index.defining_sql)

        asyncio.run(main())
        ```
    """
    return await super().get_async(
        include_columns=False,
        include_activity=include_activity,
        synapse_client=synapse_client,
    )

delete_async async

delete_async(*, synapse_client: Optional[Synapse] = None) -> None

Asynchronously delete this SearchIndex from Synapse. id must be set before calling this.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

Delete a SearchIndex by ID.

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndex

async def main():
    syn = Synapse()
    await syn.login_async()

    await SearchIndex(id="syn12345").delete_async()

asyncio.run(main())
Source code in synapseclient/models/search_index.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
async def delete_async(self, *, synapse_client: Optional[Synapse] = None) -> None:
    """Asynchronously delete this SearchIndex from Synapse. `id` must be set
    before calling this.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Example: Delete a SearchIndex by ID.
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        async def main():
            syn = Synapse()
            await syn.login_async()

            await SearchIndex(id="syn12345").delete_async()

        asyncio.run(main())
        ```
    """
    await super().delete_async(synapse_client=synapse_client)

query_async async

query_async(search_query: SearchQuery, response_parts: Optional[List[SearchQueryPart]] = None, *, job_timeout: int = 600, synapse_client: Optional[Synapse] = None) -> SearchIndexQuery

Asynchronously query this search index. Unlike a SQL-backed Table, a SearchIndex is queried with the OpenSearch Query DSL carried by a SearchQuery — not with Synapse SQL. See Query for the supported clause kinds.

PARAMETER DESCRIPTION
search_query

The OpenSearch _search body to execute against this index.

TYPE: SearchQuery

response_parts

Additional response parts to request beyond the default hits, such as the total hit count or the select columns.

TYPE: Optional[List[SearchQueryPart]] DEFAULT: None

job_timeout

The maximum amount of time to wait for the query job to complete before raising a SynapseTimeoutError.

TYPE: int DEFAULT: 600

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
SearchIndexQuery

The completed SearchIndexQuery, carrying the hits and any requested response parts.

RAISES DESCRIPTION
ValueError

If the id attribute has not been set.

Query an index for documents mentioning "alzheimer".

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
from synapseclient.models.search_dsl import Query

async def main():
    syn = Synapse()
    await syn.login_async()

    results = await SearchIndex(id="syn12345").query_async(
        search_query=SearchQuery(
            query=Query(match={"title": {"query": "alzheimer"}}),
            size=10,
        ),
        response_parts=[SearchQueryPart.TOTAL_HITS],
    )
    print(results.total_hits)
    for hit in results.hits:
        print(hit.row_id, hit.fields)

asyncio.run(main())
Source code in synapseclient/models/search_index.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Query: {self.id}"
)
async def query_async(
    self,
    search_query: "SearchQuery",
    response_parts: Optional[List["SearchQueryPart"]] = None,
    *,
    job_timeout: int = 600,
    synapse_client: Optional[Synapse] = None,
) -> "SearchIndexQuery":
    """Asynchronously query this search index. Unlike a SQL-backed Table, a
    SearchIndex is queried with the
    [OpenSearch Query DSL](https://docs.opensearch.org/latest/query-dsl/)
    carried by a [SearchQuery][synapseclient.models.SearchQuery] — not with
    Synapse SQL. See [Query][synapseclient.models.search_dsl.Query] for the
    supported clause kinds.

    Arguments:
        search_query: The OpenSearch
            [`_search`](https://docs.opensearch.org/latest/api-reference/search-apis/search/)
            body to execute against this index.
        response_parts: Additional response parts to request beyond the
            default hits, such as the total hit count or the select columns.
        job_timeout: The maximum amount of time to wait for the query job to
            complete before raising a `SynapseTimeoutError`.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The completed [SearchIndexQuery][synapseclient.models.SearchIndexQuery], carrying the `hits` and any requested response parts.

    Raises:
        ValueError: If the `id` attribute has not been set.

    Example: Query an index for documents mentioning "alzheimer".
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
        from synapseclient.models.search_dsl import Query

        async def main():
            syn = Synapse()
            await syn.login_async()

            results = await SearchIndex(id="syn12345").query_async(
                search_query=SearchQuery(
                    query=Query(match={"title": {"query": "alzheimer"}}),
                    size=10,
                ),
                response_parts=[SearchQueryPart.TOTAL_HITS],
            )
            print(results.total_hits)
            for hit in results.hits:
                print(hit.row_id, hit.fields)

        asyncio.run(main())
        ```
    """
    from synapseclient.models.search_management import SearchIndexQuery

    if not self.id:
        raise ValueError("The id attribute must be set to query a SearchIndex.")
    return await SearchIndexQuery(
        search_index_id=self.id,
        search_query=search_query,
        response_parts=response_parts or [],
    ).send_job_and_wait_async(timeout=job_timeout, synapse_client=synapse_client)

autocomplete_async async

autocomplete_async(query: Query, source: Optional[SourceFilter] = None, *, synapse_client: Optional[Synapse] = None) -> List[SearchHit]

Run a synchronous autocomplete search against this index. The autocomplete endpoint allow lists only prefix-style queries (prefix, match_phrase_prefix, or match_bool_prefix) and caps results at 8.

PARAMETER DESCRIPTION
query

The top-level OpenSearch Query DSL clause -- see Query; restricted server-side to prefix, match_phrase_prefix, or match_bool_prefix.

TYPE: Query

source

Optional source filter selecting which columns are returned on each hit.

TYPE: Optional[SourceFilter] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
List[SearchHit]

The matching SearchHits, capped at 8.

RAISES DESCRIPTION
ValueError

If the id attribute has not been set.

Autocomplete titles beginning with "alz".

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndex
from synapseclient.models.search_dsl import PrefixFieldOptions, Query

async def main():
    syn = Synapse()
    await syn.login_async()

    index = SearchIndex(id="syn12345")
    hits = await index.autocomplete_async(
        query=Query(
            prefix={"title": PrefixFieldOptions(value="alz")}
        ),
    )
    for hit in hits:
        print(hit.row_id, hit.fields)

asyncio.run(main())
Source code in synapseclient/models/search_index.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"SearchIndex_Autocomplete: {self.id}"
)
async def autocomplete_async(
    self,
    query: Query,
    source: Optional[SourceFilter] = None,
    *,
    synapse_client: Optional[Synapse] = None,
) -> List["SearchHit"]:
    """Run a synchronous autocomplete search against this index. The
    autocomplete endpoint allow lists only prefix-style queries
    ([`prefix`](https://docs.opensearch.org/latest/query-dsl/term/prefix/),
    [`match_phrase_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase-prefix/),
    or [`match_bool_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-bool-prefix/))
    and caps results at 8.

    Arguments:
        query: The top-level [OpenSearch Query DSL](https://docs.opensearch.org/latest/query-dsl/)
            clause -- see [Query][synapseclient.models.search_dsl.Query];
            restricted server-side to `prefix`, `match_phrase_prefix`, or
            `match_bool_prefix`.
        source: Optional [source filter](https://docs.opensearch.org/latest/search-plugins/searching-data/retrieve-specific-fields/)
            selecting which columns are returned on each hit.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The matching SearchHits, capped at 8.

    Raises:
        ValueError: If the ``id`` attribute has not been set.

    Example: Autocomplete titles beginning with "alz".
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex
        from synapseclient.models.search_dsl import PrefixFieldOptions, Query

        async def main():
            syn = Synapse()
            await syn.login_async()

            index = SearchIndex(id="syn12345")
            hits = await index.autocomplete_async(
                query=Query(
                    prefix={"title": PrefixFieldOptions(value="alz")}
                ),
            )
            for hit in hits:
                print(hit.row_id, hit.fields)

        asyncio.run(main())
        ```
    """
    from synapseclient.api import autocomplete_search
    from synapseclient.models.search_management import (
        SearchAutocompleteRequest,
        SearchHit,
    )

    if not self.id:
        raise ValueError("The id attribute must be set to call autocomplete.")
    request = SearchAutocompleteRequest(
        search_index_id=self.id,
        query=query,
        source=source,
    )
    response = await autocomplete_search(
        request.to_synapse_request(), synapse_client=synapse_client
    )
    return [SearchHit().fill_from_dict(h) for h in response.get("hits", []) or []]

get_permissions_async async

get_permissions_async(*, synapse_client: Optional[Synapse] = None) -> Permissions

Get the permissions that the caller has on an Entity.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Permissions

A Permissions object

Using this function:

Getting permissions for a Synapse Entity

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    permissions = await File(id="syn123").get_permissions_async()

asyncio.run(main())

Getting access types list from the Permissions object

permissions.access_types
Source code in synapseclient/models/mixins/access_control.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
async def get_permissions_async(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Permissions":
    """
    Get the [permissions][synapseclient.core.models.permission.Permissions]
    that the caller has on an Entity.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        A Permissions object


    Example: Using this function:
        Getting permissions for a Synapse Entity

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            permissions = await File(id="syn123").get_permissions_async()

        asyncio.run(main())
        ```

        Getting access types list from the Permissions object

        ```
        permissions.access_types
        ```
    """
    from synapseclient.core.models.permission import Permissions

    permissions_dict = await get_entity_permissions(
        entity_id=self.id,
        synapse_client=synapse_client,
    )
    return Permissions.from_dict(data=permissions_dict)

get_acl_async async

get_acl_async(principal_id: int = None, check_benefactor: bool = True, *, synapse_client: Optional[Synapse] = None) -> List[str]

Get the ACL that a user or group has on an Entity.

Note: If the entity does not have local sharing settings, or ACL set directly on it, this will look up the ACL on the benefactor of the entity. The benefactor is the entity that the current entity inherits its permissions from. The benefactor is usually the parent entity, but it can be any ancestor in the hierarchy. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project or Folder. If the entity already has local sharing settings, the benefactor would be itself.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group (defaults to PUBLIC users)

TYPE: int DEFAULT: None

check_benefactor

If True (default), check the benefactor for the entity to get the ACL. If False, only check the entity itself. This is useful for checking the ACL of an entity that has local sharing settings, but you want to check the ACL of the entity itself and not the benefactor it may inherit from.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
List[str]

An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array

Source code in synapseclient/models/mixins/access_control.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
async def get_acl_async(
    self,
    principal_id: int = None,
    check_benefactor: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> List[str]:
    """
    Get the [ACL][synapseclient.core.models.permission.Permissions.access_types]
    that a user or group has on an Entity.

    Note: If the entity does not have local sharing settings, or ACL set directly
    on it, this will look up the ACL on the benefactor of the entity. The
    benefactor is the entity that the current entity inherits its permissions from.
    The benefactor is usually the parent entity, but it can be any ancestor in the
    hierarchy. For example, a newly created Project will be its own benefactor,
    while a new FileEntity's benefactor will start off as its containing Project or
    Folder. If the entity already has local sharing settings, the benefactor would
    be itself.

    Arguments:
        principal_id: Identifier of a user or group (defaults to PUBLIC users)
        check_benefactor: If True (default), check the benefactor for the entity
            to get the ACL. If False, only check the entity itself.
            This is useful for checking the ACL of an entity that has local sharing
            settings, but you want to check the ACL of the entity itself and not
            the benefactor it may inherit from.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An array containing some combination of
            ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
            'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
            or an empty array
    """
    return await get_entity_acl_list(
        entity_id=self.id,
        principal_id=str(principal_id) if principal_id is not None else None,
        check_benefactor=check_benefactor,
        synapse_client=synapse_client,
    )

set_permissions_async async

set_permissions_async(principal_id: int = None, access_type: List[str] = None, modify_benefactor: bool = False, warn_if_inherits: bool = True, overwrite: bool = True, *, synapse_client: Optional[Synapse] = None) -> Dict[str, Union[str, list]]

Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group. 273948 is for all registered Synapse users and 273949 is for public access. None implies public access.

TYPE: int DEFAULT: None

access_type

Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

Defaults to ['READ', 'DOWNLOAD']

TYPE: List[str] DEFAULT: None

modify_benefactor

Set as True when modifying a benefactor's ACL. The term 'benefactor' is used to indicate which Entity an Entity inherits its ACL from. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project. If the entity already has local sharing settings the benefactor would be itself. It may also be the immediate parent, somewhere in the parent tree, or the project itself.

TYPE: bool DEFAULT: False

warn_if_inherits

When modify_benefactor is True, this does not have any effect. When modify_benefactor is False, and warn_if_inherits is True, a warning log message is produced if the benefactor for the entity you passed into the function is not itself, i.e., it's the parent folder, or another entity in the parent tree.

TYPE: bool DEFAULT: True

overwrite

By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Dict[str, Union[str, list]]
Setting permissions

Grant all registered users download access

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").set_permissions_async(principal_id=273948, access_type=['READ','DOWNLOAD'])

asyncio.run(main())

Grant the public view access

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").set_permissions_async(principal_id=273949, access_type=['READ'])

asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
async def set_permissions_async(
    self,
    principal_id: int = None,
    access_type: List[str] = None,
    modify_benefactor: bool = False,
    warn_if_inherits: bool = True,
    overwrite: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> Dict[str, Union[str, list]]:
    """
    Sets permission that a user or group has on an Entity.
    An Entity may have its own ACL or inherit its ACL from a benefactor.

    Arguments:
        principal_id: Identifier of a user or group. `273948` is for all
            registered Synapse users and `273949` is for public access.
            None implies public access.
        access_type: Type of permission to be granted. One or more of CREATE,
            READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

            **Defaults to ['READ', 'DOWNLOAD']**
        modify_benefactor: Set as True when modifying a benefactor's ACL. The term
            'benefactor' is used to indicate which Entity an Entity inherits its
            ACL from. For example, a newly created Project will be its own
            benefactor, while a new FileEntity's benefactor will start off as its
            containing Project. If the entity already has local sharing settings
            the benefactor would be itself. It may also be the immediate parent,
            somewhere in the parent tree, or the project itself.
        warn_if_inherits: When `modify_benefactor` is True, this does not have any
            effect. When `modify_benefactor` is False, and `warn_if_inherits` is
            True, a warning log message is produced if the benefactor for the
            entity you passed into the function is not itself, i.e., it's the
            parent folder, or another entity in the parent tree.
        overwrite: By default this function overwrites existing permissions for
            the specified user. Set this flag to False to add new permissions
            non-destructively.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An Access Control List object matching <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/AccessControlList.html>.

    Example: Setting permissions
        Grant all registered users download access

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").set_permissions_async(principal_id=273948, access_type=['READ','DOWNLOAD'])

        asyncio.run(main())
        ```

        Grant the public view access

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").set_permissions_async(principal_id=273949, access_type=['READ'])

        asyncio.run(main())
        ```
    """
    if access_type is None:
        access_type = ["READ", "DOWNLOAD"]

    return await set_entity_permissions(
        entity_id=self.id,
        principal_id=str(principal_id) if principal_id is not None else None,
        access_type=access_type,
        modify_benefactor=modify_benefactor,
        warn_if_inherits=warn_if_inherits,
        overwrite=overwrite,
        synapse_client=synapse_client,
    )

delete_permissions_async async

delete_permissions_async(include_self: bool = True, include_container_content: bool = False, recursive: bool = False, target_entity_types: Optional[List[str]] = None, dry_run: bool = False, show_acl_details: bool = True, show_files_in_containers: bool = True, *, synapse_client: Optional[Synapse] = None, _benefactor_tracker: Optional[BenefactorTracker] = None) -> None

Delete the entire Access Control List (ACL) for a given Entity. This is not scoped to a specific user or group, but rather removes all permissions associated with the Entity. After this operation, the Entity will inherit permissions from its benefactor, which is typically its parent entity or the Project it belongs to.

In order to remove permissions for a specific user or group, you should use the set_permissions_async method with the access_type set to an empty list.

By default, Entities such as FileEntity and Folder inherit their permission from their containing Project. For such Entities the Project is the Entity's 'benefactor'. This permission inheritance can be overridden by creating an ACL for the Entity. When this occurs the Entity becomes its own benefactor and all permission are determined by its own ACL.

If the ACL of an Entity is deleted, then its benefactor will automatically be set to its parent's benefactor.

Special notice for Projects: The ACL for a Project cannot be deleted, you must individually update or revoke the permissions for each user or group.

PARAMETER DESCRIPTION
include_self

If True (default), delete the ACL of the current entity. If False, skip deleting the ACL of the current entity.

TYPE: bool DEFAULT: True

include_container_content

If True, delete ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when deleting ACLs. Allowed values are "folder", "file", "project", "table", "entityview", "materializedview", "virtualtable", "dataset", "datasetcollection", "submissionview" (case-insensitive). If None, defaults to ["folder", "file"]. This does not affect the entity type of the current entity, which is always processed if include_self=True.

TYPE: Optional[List[str]] DEFAULT: None

dry_run

If True, log the changes that would be made instead of actually performing the deletions. When enabled, all ACL deletion operations are simulated and logged at info level. Defaults to False.

TYPE: bool DEFAULT: False

show_acl_details

When dry_run=True, controls whether current ACL details are displayed for entities that will have their permissions changed. If True (default), shows detailed ACL information. If False, hides ACL details for cleaner output. Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

show_files_in_containers

When dry_run=True, controls whether files within containers are displayed in the preview. If True (default), shows all files. If False, hides files when their only change is benefactor inheritance (but still shows files with local ACLs being deleted). Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

_benefactor_tracker

Internal use tracker for managing benefactor relationships. Used for recursive functionality to track which entities will be affected

TYPE: Optional[BenefactorTracker] DEFAULT: None

RETURNS DESCRIPTION
None

None

RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues or if the entity already inherits permissions.

Exception

For any other errors that may occur during the process.

Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to call this method.

Delete permissions for a single entity
import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").delete_permissions_async()

asyncio.run(main())
Delete permissions recursively for a folder and all its children
import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    # Delete permissions for this folder only (does not affect children)
    await Folder(id="syn123").delete_permissions_async()

    # Delete permissions for all files and folders directly within this folder,
    # but not the folder itself
    await Folder(id="syn123").delete_permissions_async(
        include_self=False,
        include_container_content=True
    )

    # Delete permissions for all items in the entire hierarchy (folders and their files)
    # Both recursive and include_container_content must be True
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True
    )

    # Delete permissions only for folder entities within this folder recursively
    # and their contents
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["folder"]
    )

    # Delete permissions only for files within this folder and all subfolders
    await Folder(id="syn123").delete_permissions_async(
        include_self=False,
        recursive=True,
        include_container_content=True,
        target_entity_types=["file"]
    )

    # Delete permissions for specific entity types (e.g., tables and views)
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["table", "entityview", "materializedview"]
    )

    # Dry run example: Log what would be deleted without making changes
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        dry_run=True
    )
asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
async def delete_permissions_async(
    self,
    include_self: bool = True,
    include_container_content: bool = False,
    recursive: bool = False,
    target_entity_types: Optional[List[str]] = None,
    dry_run: bool = False,
    show_acl_details: bool = True,
    show_files_in_containers: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
    _benefactor_tracker: Optional[BenefactorTracker] = None,
) -> None:
    """
    Delete the entire Access Control List (ACL) for a given Entity. This is not
    scoped to a specific user or group, but rather removes all permissions
    associated with the Entity. After this operation, the Entity will inherit
    permissions from its benefactor, which is typically its parent entity or
    the Project it belongs to.

    In order to remove permissions for a specific user or group, you
    should use the `set_permissions_async` method with the `access_type` set to
    an empty list.

    By default, Entities such as FileEntity and Folder inherit their permission from
    their containing Project. For such Entities the Project is the Entity's 'benefactor'.
    This permission inheritance can be overridden by creating an ACL for the Entity.
    When this occurs the Entity becomes its own benefactor and all permission are
    determined by its own ACL.

    If the ACL of an Entity is deleted, then its benefactor will automatically be set
    to its parent's benefactor.

    **Special notice for Projects:** The ACL for a Project cannot be deleted, you
    must individually update or revoke the permissions for each user or group.

    Arguments:
        include_self: If True (default), delete the ACL of the current entity.
            If False, skip deleting the ACL of the current entity.
        include_container_content: If True, delete ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        target_entity_types: Specify which entity types to process when deleting ACLs.
            Allowed values are "folder", "file", "project", "table", "entityview",
            "materializedview", "virtualtable", "dataset", "datasetcollection",
            "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
            This does not affect the entity type of the current entity, which is always
            processed if `include_self=True`.
        dry_run: If True, log the changes that would be made instead of actually
            performing the deletions. When enabled, all ACL deletion operations are
            simulated and logged at info level. Defaults to False.
        show_acl_details: When dry_run=True, controls whether current ACL details are
            displayed for entities that will have their permissions changed. If True (default),
            shows detailed ACL information. If False, hides ACL details for cleaner output.
            Has no effect when dry_run=False.
        show_files_in_containers: When dry_run=True, controls whether files within containers
            are displayed in the preview. If True (default), shows all files. If False, hides
            files when their only change is benefactor inheritance (but still shows files with
            local ACLs being deleted). Has no effect when dry_run=False.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.
        _benefactor_tracker: Internal use tracker for managing benefactor relationships.
            Used for recursive functionality to track which entities will be affected

    Returns:
        None

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues or if the entity already inherits permissions.
        Exception: For any other errors that may occur during the process.

    Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to
    call this method.

    Example: Delete permissions for a single entity
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").delete_permissions_async()

        asyncio.run(main())
        ```

    Example: Delete permissions recursively for a folder and all its children
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            # Delete permissions for this folder only (does not affect children)
            await Folder(id="syn123").delete_permissions_async()

            # Delete permissions for all files and folders directly within this folder,
            # but not the folder itself
            await Folder(id="syn123").delete_permissions_async(
                include_self=False,
                include_container_content=True
            )

            # Delete permissions for all items in the entire hierarchy (folders and their files)
            # Both recursive and include_container_content must be True
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True
            )

            # Delete permissions only for folder entities within this folder recursively
            # and their contents
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )

            # Delete permissions only for files within this folder and all subfolders
            await Folder(id="syn123").delete_permissions_async(
                include_self=False,
                recursive=True,
                include_container_content=True,
                target_entity_types=["file"]
            )

            # Delete permissions for specific entity types (e.g., tables and views)
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["table", "entityview", "materializedview"]
            )

            # Dry run example: Log what would be deleted without making changes
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                dry_run=True
            )
        asyncio.run(main())
        ```
    """
    if not self.id:
        raise ValueError("The entity must have an ID to delete permissions.")

    client = Synapse.get_client(synapse_client=synapse_client)

    if include_self and self.__class__.__name__.lower() == "project":
        client.logger.warning(
            "The ACL for a Project cannot be deleted, you must individually update or "
            "revoke the permissions for each user or group. Continuing without deleting "
            "the Project's ACL."
        )
        include_self = False

    normalized_types = self._normalize_target_entity_types(target_entity_types)

    is_top_level = not _benefactor_tracker
    benefactor_tracker = _benefactor_tracker or BenefactorTracker()

    should_process_children = (recursive or include_container_content) and hasattr(
        self, "sync_from_synapse_async"
    )
    all_entities = [self] if include_self else []

    custom_message = "Deleting ACLs [Dry Run]..." if dry_run else "Deleting ACLs..."
    with shared_download_progress_bar(
        file_size=1, synapse_client=client, custom_message=custom_message, unit=None
    ) as progress_bar:
        if progress_bar:
            progress_bar.update(1)  # Initial setup complete

        if should_process_children:
            if recursive and not include_container_content:
                raise ValueError(
                    "When recursive=True, include_container_content must also be True. "
                    "Setting recursive=True with include_container_content=False has no effect."
                )

            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()

            all_entities = await self._collect_entities(
                client=client,
                target_entity_types=normalized_types,
                include_container_content=include_container_content,
                recursive=recursive,
                progress_bar=progress_bar,
            )
            if progress_bar:
                progress_bar.update(1)

            entity_ids = [entity.id for entity in all_entities if entity.id]
            if entity_ids:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await benefactor_tracker.track_entity_benefactor(
                    entity_ids=entity_ids,
                    synapse_client=client,
                    progress_bar=progress_bar,
                )
            else:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                    progress_bar.update(1)

        if is_top_level:
            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()
            await self._build_and_log_run_tree(
                client=client,
                benefactor_tracker=benefactor_tracker,
                collected_entities=all_entities,
                include_self=include_self,
                show_acl_details=show_acl_details,
                show_files_in_containers=show_files_in_containers,
                progress_bar=progress_bar,
                dry_run=dry_run,
            )

        if dry_run:
            return

        if include_self:
            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()
            await self._delete_current_entity_acl(
                client=client,
                benefactor_tracker=benefactor_tracker,
                progress_bar=progress_bar,
            )

        if should_process_children:
            if include_container_content:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await self._process_container_contents(
                    client=client,
                    target_entity_types=normalized_types,
                    benefactor_tracker=benefactor_tracker,
                    progress_bar=progress_bar,
                    recursive=recursive,
                    include_container_content=include_container_content,
                )
                if progress_bar:
                    progress_bar.update(1)  # Process container contents complete

list_acl_async async

list_acl_async(recursive: bool = False, include_container_content: bool = False, target_entity_types: Optional[List[str]] = None, log_tree: bool = False, *, synapse_client: Optional[Synapse] = None, _progress_bar: Optional[tqdm] = None) -> AclListResult

List the Access Control Lists (ACLs) for this entity and optionally its children.

This function returns the local sharing settings for the entity and optionally its children. It provides a mapping of all ACLs for the given container/entity.

Important Note: This function returns the LOCAL sharing settings only, not the effective permissions that each Synapse User ID/Team has on the entities. More permissive permissions could be granted via a Team that the user has access to that has permissions on the entity, or through inheritance from parent entities.

PARAMETER DESCRIPTION
recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

include_container_content

If True, include ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when listing ACLs. Allowed values are "folder", "file", "project", "table", "entityview", "materializedview", "virtualtable", "dataset", "datasetcollection", "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].

TYPE: Optional[List[str]] DEFAULT: None

log_tree

If True, logs the ACL results to console in ASCII tree format showing entity hierarchies and their ACL permissions in a tree-like structure. Defaults to False.

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

_progress_bar

Internal parameter. Progress bar instance to use for updates when called recursively. Should not be used by external callers.

TYPE: Optional[tqdm] DEFAULT: None

RETURNS DESCRIPTION
AclListResult

An AclListResult object containing a structured representation of ACLs where:

AclListResult
  • entity_acls: A list of EntityAcl objects, each representing one entity's ACL
AclListResult
  • Each EntityAcl contains acl_entries (a list of AclEntry objects)
AclListResult
  • Each AclEntry contains the principal_id and their list of permissions
RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues accessing ACLs.

Exception

For any other errors that may occur during the process.

List ACLs for a single entity
import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    acl_result = await File(id="syn123").list_acl_async()
    print(acl_result)

    # Access entity ACLs (entity_acls is a list, not a dict)
    for entity_acl in acl_result.all_entity_acls:
        if entity_acl.entity_id == "syn123":
            # Access individual ACL entries
            for acl_entry in entity_acl.acl_entries:
                if acl_entry.principal_id == "273948":
                    print(f"Principal 273948 has permissions: {acl_entry.permissions}")

    # I can also access the ACL for the file itself
    print(acl_result.entity_acl)

    print(acl_result)

asyncio.run(main())
List ACLs recursively for a folder and all its children
import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True
    )

    # Access each entity's ACL (entity_acls is a list)
    for entity_acl in acl_result.all_entity_acls:
        print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

    # I can also access the ACL for the folder itself
    print(acl_result.entity_acl)

    # List ACLs for only folder entities
    folder_acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["folder"]
    )

    # List ACLs for specific entity types (e.g., tables and views)
    table_view_acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["table", "entityview", "materializedview"]
    )

asyncio.run(main())
List ACLs with ASCII tree visualization

When log_tree=True, the ACLs will be logged in a tree format. Additionally, the ascii_tree attribute of the AclListResult will contain the ASCII tree representation of the ACLs.

import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        log_tree=True, # Enable ASCII tree logging
    )

    # The ASCII tree representation of the ACLs will also be available
    # in acl_result.ascii_tree
    print(acl_result.ascii_tree)

asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
async def list_acl_async(
    self,
    recursive: bool = False,
    include_container_content: bool = False,
    target_entity_types: Optional[List[str]] = None,
    log_tree: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
    _progress_bar: Optional[tqdm] = None,  # Internal parameter for recursive calls
) -> AclListResult:
    """
    List the Access Control Lists (ACLs) for this entity and optionally its children.

    This function returns the local sharing settings for the entity and optionally
    its children. It provides a mapping of all ACLs for the given container/entity.

    **Important Note:** This function returns the LOCAL sharing settings only, not
    the effective permissions that each Synapse User ID/Team has on the entities.
    More permissive permissions could be granted via a Team that the user has access
    to that has permissions on the entity, or through inheritance from parent entities.

    Arguments:
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        include_container_content: If True, include ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        target_entity_types: Specify which entity types to process when listing ACLs.
            Allowed values are "folder", "file", "project", "table", "entityview",
            "materializedview", "virtualtable", "dataset", "datasetcollection",
            "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
        log_tree: If True, logs the ACL results to console in ASCII tree format showing
            entity hierarchies and their ACL permissions in a tree-like structure.
            Defaults to False.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.
        _progress_bar: Internal parameter. Progress bar instance to use for updates
            when called recursively. Should not be used by external callers.

    Returns:
        An AclListResult object containing a structured representation of ACLs where:
        - entity_acls: A list of EntityAcl objects, each representing one entity's ACL
        - Each EntityAcl contains acl_entries (a list of AclEntry objects)
        - Each AclEntry contains the principal_id and their list of permissions

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues accessing ACLs.
        Exception: For any other errors that may occur during the process.

    Example: List ACLs for a single entity
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await File(id="syn123").list_acl_async()
            print(acl_result)

            # Access entity ACLs (entity_acls is a list, not a dict)
            for entity_acl in acl_result.all_entity_acls:
                if entity_acl.entity_id == "syn123":
                    # Access individual ACL entries
                    for acl_entry in entity_acl.acl_entries:
                        if acl_entry.principal_id == "273948":
                            print(f"Principal 273948 has permissions: {acl_entry.permissions}")

            # I can also access the ACL for the file itself
            print(acl_result.entity_acl)

            print(acl_result)

        asyncio.run(main())
        ```

    Example: List ACLs recursively for a folder and all its children
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True
            )

            # Access each entity's ACL (entity_acls is a list)
            for entity_acl in acl_result.all_entity_acls:
                print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

            # I can also access the ACL for the folder itself
            print(acl_result.entity_acl)

            # List ACLs for only folder entities
            folder_acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )

            # List ACLs for specific entity types (e.g., tables and views)
            table_view_acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["table", "entityview", "materializedview"]
            )

        asyncio.run(main())
        ```

    Example: List ACLs with ASCII tree visualization
        When `log_tree=True`, the ACLs will be logged in a tree format. Additionally,
        the `ascii_tree` attribute of the AclListResult will contain the ASCII tree
        representation of the ACLs.

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                log_tree=True, # Enable ASCII tree logging
            )

            # The ASCII tree representation of the ACLs will also be available
            # in acl_result.ascii_tree
            print(acl_result.ascii_tree)

        asyncio.run(main())
        ```
    """
    if not self.id:
        raise ValueError("The entity must have an ID to list ACLs.")

    normalized_types = self._normalize_target_entity_types(target_entity_types)
    client = Synapse.get_client(synapse_client=synapse_client)

    all_acls: Dict[str, Dict[str, List[str]]] = {}
    all_entities = []

    # Only update progress bar for self ACL if we're the top-level call (not recursive)
    # When _progress_bar is passed, it means this is a recursive call and the parent
    # is managing progress updates
    update_progress_for_self = _progress_bar is None
    acl = await self._get_current_entity_acl(
        client=client,
        progress_bar=_progress_bar if update_progress_for_self else None,
    )
    if acl is not None:
        all_acls[self.id] = acl
    all_entities.append(self)

    should_process_children = (recursive or include_container_content) and hasattr(
        self, "sync_from_synapse_async"
    )

    if should_process_children and (recursive and not include_container_content):
        raise ValueError(
            "When recursive=True, include_container_content must also be True. "
            "Setting recursive=True with include_container_content=False has no effect."
        )

    if should_process_children and _progress_bar is None:
        with shared_download_progress_bar(
            file_size=1,
            synapse_client=client,
            custom_message="Collecting ACLs...",
            unit=None,
        ) as progress_bar:
            await self._process_children_with_progress(
                client=client,
                normalized_types=normalized_types,
                include_container_content=include_container_content,
                recursive=recursive,
                all_entities=all_entities,
                all_acls=all_acls,
                progress_bar=progress_bar,
            )
            # Ensure progress bar reaches 100% completion
            if progress_bar:
                remaining = (
                    progress_bar.total - progress_bar.n
                    if progress_bar.total > progress_bar.n
                    else 0
                )
                if remaining > 0:
                    progress_bar.update(remaining)
    elif should_process_children:
        await self._process_children_with_progress(
            client=client,
            normalized_types=normalized_types,
            include_container_content=include_container_content,
            recursive=recursive,
            all_entities=all_entities,
            all_acls=all_acls,
            progress_bar=_progress_bar,
        )
    current_acl = all_acls.get(self.id)
    acl_result = AclListResult.from_dict(
        all_acl_dict=all_acls, current_acl_dict=current_acl
    )

    if log_tree:
        logged_tree = await self._log_acl_tree(acl_result, all_entities, client)
        acl_result.ascii_tree = logged_tree

    return acl_result

Supporting types

synapseclient.models.SearchQuery dataclass

The body of an OpenSearch _search request, narrowed to the top-level keys Synapse accepts. Each slot's contents are pass-through OpenSearch query DSL, typed by the TypedDict shapes in synapseclient.models.search_dsl.

Represents a Synapse SearchQuery.

Source code in synapseclient/models/search_management.py
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
@dataclass
class SearchQuery:
    """The body of an OpenSearch [`_search`](https://docs.opensearch.org/latest/api-reference/search-apis/search/)
    request, narrowed to the top-level keys Synapse accepts. Each slot's
    contents are pass-through [OpenSearch query DSL](https://docs.opensearch.org/latest/query-dsl/),
    typed by the `TypedDict` shapes in `synapseclient.models.search_dsl`.

    Represents a [Synapse SearchQuery](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/SearchQuery.html).
    """

    query: Optional[Query] = None
    """Required. The [OpenSearch query DSL](https://docs.opensearch.org/latest/query-dsl/)
    clause -- see [Query][synapseclient.models.search_dsl.Query] for every
    supported clause kind. Use [`{"match_all": {}}`](https://docs.opensearch.org/latest/query-dsl/match-all/)
    to match all documents. See also
    [query vs. filter context](https://docs.opensearch.org/latest/query-dsl/query-filter-context/)."""

    post_filter: Optional[Query] = None
    """Optional. Same DSL shape as `query` (see
    [Query][synapseclient.models.search_dsl.Query]), applied *after*
    aggregations are computed. For the distinction between filtering hits and
    filtering aggregations, see
    [query vs. filter context](https://docs.opensearch.org/latest/query-dsl/query-filter-context/)."""

    aggregations: Optional[Dict[str, Aggregation]] = None
    """Optional. Map of caller-chosen name to
    [aggregation][synapseclient.models.search_dsl.Aggregation] definition. The
    raw aggregation result comes back on `SearchIndexQuery.aggregation_results`.
    For the facet-counting pattern (a `terms` aggregation alongside
    `post_filter`), see the
    [faceted search tutorial](https://docs.opensearch.org/latest/tutorials/faceted-search/#maintaining-facet-options-during-filtering)."""

    highlight: Optional[Highlight] = None
    """Optional. Adds per-field
    [snippet fragments](https://docs.opensearch.org/latest/search-plugins/searching-data/highlight/)
    (matched terms wrapped in `<em>` / `</em>` by default) to each hit's
    highlights."""

    collapse: Optional[FieldCollapse] = None
    """Optional. [Groups the result list](https://docs.opensearch.org/latest/search-plugins/searching-data/collapse-search/)
    so only one hit is returned per distinct value of a field."""

    rescore: Optional[Rescore] = None
    """Optional. [Re-ranks](https://docs.opensearch.org/latest/query-dsl/rescore/)
    the top hits returned by `query` using a secondary scoring query."""

    sort: Optional[List[Any]] = None
    """Optional. Result [ordering](https://docs.opensearch.org/latest/search-plugins/searching-data/sort/),
    in native OpenSearch sort shape (a string column name,
    `{column: "asc|desc"}`, or `{column: {order: ..., mode: ..., missing: ...}}`)
    applied in order. Only the `field` and `_score` sort kinds are accepted --
    script and geo-distance sorts are rejected server-side. The pseudo-column
    `_score` sorts by relevance. When omitted, results are sorted by relevance
    descending."""

    source: Optional[SourceFilter] = None
    """Optional. [Source filter](https://docs.opensearch.org/latest/search-plugins/searching-data/retrieve-specific-fields/)
    selecting which columns are returned on each hit. Serialized as
    `_source`."""

    from_: Optional[int] = None
    """Optional. Zero-based
    [pagination](https://docs.opensearch.org/latest/search-plugins/searching-data/paginate/)
    offset; default 0. Ignored when `search_after` is supplied. Serialized as
    `from`."""

    size: Optional[int] = None
    """Optional. Maximum number of hits to return per
    [page](https://docs.opensearch.org/latest/search-plugins/searching-data/paginate/).
    Default 25. Maximum 100 (larger values are silently capped)."""

    search_after: Optional[List[Optional[ScalarValue]]] = None
    """Optional. Opaque
    [cursor](https://docs.opensearch.org/latest/search-plugins/searching-data/paginate/)
    emitted as `next_search_after` on the previous response. Pass back
    unchanged. When supplied, `from_` is ignored."""

    def fill_from_dict(self, data: Dict[str, Any]) -> "Self":
        self.query = data.get("query", None)
        self.post_filter = data.get("post_filter", None)
        self.aggregations = data.get("aggregations", None)
        self.highlight = data.get("highlight", None)
        self.collapse = data.get("collapse", None)
        self.rescore = data.get("rescore", None)
        self.sort = data.get("sort", None)
        self.source = data.get("_source", None)
        self.from_ = data.get("from", None)
        self.size = data.get("size", None)
        self.search_after = data.get("search_after", None)
        return self

    def to_synapse_request(self) -> Dict[str, Any]:
        body = {
            "query": self.query,
            "post_filter": self.post_filter,
            "aggregations": self.aggregations,
            "highlight": self.highlight,
            "collapse": self.collapse,
            "rescore": self.rescore,
            "sort": self.sort,
            "_source": self.source,
            "from": self.from_,
            "size": self.size,
            "search_after": self.search_after,
        }
        delete_none_keys(body)
        return body

Attributes

query class-attribute instance-attribute

query: Optional[Query] = None

Required. The OpenSearch query DSL clause -- see Query for every supported clause kind. Use {"match_all": {}} to match all documents. See also query vs. filter context.

post_filter class-attribute instance-attribute

post_filter: Optional[Query] = None

Optional. Same DSL shape as query (see Query), applied after aggregations are computed. For the distinction between filtering hits and filtering aggregations, see query vs. filter context.

aggregations class-attribute instance-attribute

aggregations: Optional[Dict[str, Aggregation]] = None

Optional. Map of caller-chosen name to aggregation definition. The raw aggregation result comes back on SearchIndexQuery.aggregation_results. For the facet-counting pattern (a terms aggregation alongside post_filter), see the faceted search tutorial.

highlight class-attribute instance-attribute

highlight: Optional[Highlight] = None

Optional. Adds per-field snippet fragments (matched terms wrapped in <em> / </em> by default) to each hit's highlights.

collapse class-attribute instance-attribute

collapse: Optional[FieldCollapse] = None

Optional. Groups the result list so only one hit is returned per distinct value of a field.

rescore class-attribute instance-attribute

rescore: Optional[Rescore] = None

Optional. Re-ranks the top hits returned by query using a secondary scoring query.

sort class-attribute instance-attribute

sort: Optional[List[Any]] = None

Optional. Result ordering, in native OpenSearch sort shape (a string column name, {column: "asc|desc"}, or {column: {order: ..., mode: ..., missing: ...}}) applied in order. Only the field and _score sort kinds are accepted -- script and geo-distance sorts are rejected server-side. The pseudo-column _score sorts by relevance. When omitted, results are sorted by relevance descending.

source class-attribute instance-attribute

source: Optional[SourceFilter] = None

Optional. Source filter selecting which columns are returned on each hit. Serialized as _source.

from_ class-attribute instance-attribute

from_: Optional[int] = None

Optional. Zero-based pagination offset; default 0. Ignored when search_after is supplied. Serialized as from.

size class-attribute instance-attribute

size: Optional[int] = None

Optional. Maximum number of hits to return per page. Default 25. Maximum 100 (larger values are silently capped).

search_after class-attribute instance-attribute

search_after: Optional[List[Optional[ScalarValue]]] = None

Optional. Opaque cursor emitted as next_search_after on the previous response. Pass back unchanged. When supplied, from_ is ignored.

synapseclient.models.SearchQueryPart

Bases: str, Enum

Optional response parts for a SearchQuery beyond default HITS.

These are values for the responseParts field on a SearchIndexQuery.

Source code in synapseclient/models/search_management.py
75
76
77
78
79
80
81
82
83
class SearchQueryPart(str, Enum):
    """Optional response parts for a SearchQuery beyond default HITS.

    These are values for the `responseParts` field on a SearchIndexQuery.
    """

    HITS = "HITS"
    TOTAL_HITS = "TOTAL_HITS"
    SELECT_COLUMNS = "SELECT_COLUMNS"

synapseclient.models.SearchIndexQuery dataclass

Bases: AsynchronousCommunicator

An async request to query a SearchIndex's OpenSearch index.

Inherits from AsynchronousCommunicator: call send_job_and_wait_async() to submit the job, poll the Synapse async job service, and populate response fields (hits, total_hits, select_columns, aggregation_results, next_search_after, offset) on this same instance.

The search_query body is an OpenSearch _search request -- see SearchQuery for the allowlisted top-level keys and Query for the query DSL clause kinds.

Represents a Synapse SearchIndexQuery.

Run a search query.

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import SearchIndexQuery, SearchQuery, SearchQueryPart

async def main():
    Synapse().login()
    query = SearchIndexQuery(
        search_index_id="syn22806626",
        search_query=SearchQuery(
            query={"match": {"title": {"query": "alzheimer"}}},
            size=10,
        ),
        response_parts=[SearchQueryPart.HITS, SearchQueryPart.TOTAL_HITS],
    )
    await query.send_job_and_wait_async()
    print(query.total_hits, len(query.hits))

asyncio.run(main())
Source code in synapseclient/models/search_management.py
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
@dataclass
class SearchIndexQuery(AsynchronousCommunicator):
    """An async request to query a SearchIndex's OpenSearch index.

    Inherits from `AsynchronousCommunicator`: call `send_job_and_wait_async()` to
    submit the job, poll the Synapse async job service, and populate response
    fields (`hits`, `total_hits`, `select_columns`, `aggregation_results`,
    `next_search_after`, `offset`) on this same instance.

    The `search_query` body is an OpenSearch
    [`_search`](https://docs.opensearch.org/latest/api-reference/search-apis/search/)
    request -- see [SearchQuery][synapseclient.models.SearchQuery] for the
    allowlisted top-level keys and
    [Query][synapseclient.models.search_dsl.Query] for the
    [query DSL](https://docs.opensearch.org/latest/query-dsl/) clause kinds.

    Represents a [Synapse SearchIndexQuery](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/table/SearchIndexQuery.html).

    Example: Run a search query.
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import SearchIndexQuery, SearchQuery, SearchQueryPart

        async def main():
            Synapse().login()
            query = SearchIndexQuery(
                search_index_id="syn22806626",
                search_query=SearchQuery(
                    query={"match": {"title": {"query": "alzheimer"}}},
                    size=10,
                ),
                response_parts=[SearchQueryPart.HITS, SearchQueryPart.TOTAL_HITS],
            )
            await query.send_job_and_wait_async()
            print(query.total_hits, len(query.hits))

        asyncio.run(main())
        ```
    """

    concrete_type: str = concrete_types.SEARCH_INDEX_QUERY
    """The Synapse concrete type identifying this async request."""

    search_index_id: Optional[str] = None
    """The ID of the SearchIndex entity to query."""

    search_query: Optional[SearchQuery] = None
    """The SearchQuery (OpenSearch `_search` body) to execute against the index."""

    response_parts: Optional[List[SearchQueryPart]] = field(default_factory=list)
    """Optional list of additional response parts beyond default HITS."""

    hits: Optional[List[SearchHit]] = field(default_factory=list)
    """Response: matching documents. Populated after `send_job_and_wait_async()`."""

    total_hits: Optional[int] = None
    """Response: total number of matching documents. Populated when
    SearchQueryPart.TOTAL_HITS is requested."""

    select_columns: Optional[List[SelectColumn]] = field(default_factory=list)
    """Response: columns represented in each hit's fields, in SELECT-clause
    order. Populated when SearchQueryPart.SELECT_COLUMNS is requested."""

    aggregation_results: Optional[Dict[str, Any]] = None
    """Response: the raw OpenSearch
    [aggregations](https://docs.opensearch.org/latest/aggregations/) response,
    with field references rewritten back to column names. Populated whenever the
    request supplied `search_query.aggregations`. Kept as an opaque JSON object
    because its shape mirrors whichever aggregations were requested."""

    next_search_after: Optional[List[Optional[ScalarValue]]] = None
    """Response: opaque
    [cursor](https://docs.opensearch.org/latest/search-plugins/searching-data/paginate/)
    for the next page. Pass back unchanged on the next request as
    `search_query.search_after`. Null when there are no further pages."""

    offset: Optional[int] = None
    """Response: zero-based pagination offset echoed from the request."""

    def to_synapse_request(self) -> Dict[str, Any]:
        """Convert to the SearchIndexQuery body for the async-job /start endpoint."""
        body = {
            "concreteType": self.concrete_type,
            "searchIndexId": self.search_index_id,
            "searchQuery": (
                self.search_query.to_synapse_request() if self.search_query else None
            ),
            "responseParts": (
                [p.value for p in self.response_parts] if self.response_parts else None
            ),
        }
        delete_none_keys(body)
        return body

    def fill_from_dict(self, synapse_response: Dict[str, Any]) -> "Self":
        """Populate response fields from a SearchQueryResults body.

        Called by `AsynchronousCommunicator.send_job_and_wait_async()` once the
        async job completes. Leaves request fields untouched.

        Modeled from [Synapse SearchQueryResults](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/SearchQueryResults.html).
        """
        self.hits = [
            SearchHit().fill_from_dict(h)
            for h in synapse_response.get("hits", []) or []
        ]
        self.total_hits = synapse_response.get("totalHits", None)
        self.select_columns = [
            SelectColumn.fill_from_dict(c)
            for c in synapse_response.get("selectColumns", []) or []
        ]
        self.aggregation_results = synapse_response.get("aggregationResults", None)
        self.next_search_after = synapse_response.get("nextSearchAfter", None)
        self.offset = synapse_response.get("offset", None)
        return self

Attributes

concrete_type class-attribute instance-attribute

concrete_type: str = concrete_types.SEARCH_INDEX_QUERY

The Synapse concrete type identifying this async request.

search_index_id class-attribute instance-attribute

search_index_id: Optional[str] = None

The ID of the SearchIndex entity to query.

search_query class-attribute instance-attribute

search_query: Optional[SearchQuery] = None

The SearchQuery (OpenSearch _search body) to execute against the index.

response_parts class-attribute instance-attribute

response_parts: Optional[List[SearchQueryPart]] = field(default_factory=list)

Optional list of additional response parts beyond default HITS.

hits class-attribute instance-attribute

hits: Optional[List[SearchHit]] = field(default_factory=list)

Response: matching documents. Populated after send_job_and_wait_async().

total_hits class-attribute instance-attribute

total_hits: Optional[int] = None

Response: total number of matching documents. Populated when SearchQueryPart.TOTAL_HITS is requested.

select_columns class-attribute instance-attribute

select_columns: Optional[List[SelectColumn]] = field(default_factory=list)

Response: columns represented in each hit's fields, in SELECT-clause order. Populated when SearchQueryPart.SELECT_COLUMNS is requested.

aggregation_results class-attribute instance-attribute

aggregation_results: Optional[Dict[str, Any]] = None

Response: the raw OpenSearch aggregations response, with field references rewritten back to column names. Populated whenever the request supplied search_query.aggregations. Kept as an opaque JSON object because its shape mirrors whichever aggregations were requested.

next_search_after class-attribute instance-attribute

next_search_after: Optional[List[Optional[ScalarValue]]] = None

Response: opaque cursor for the next page. Pass back unchanged on the next request as search_query.search_after. Null when there are no further pages.

offset class-attribute instance-attribute

offset: Optional[int] = None

Response: zero-based pagination offset echoed from the request.

synapseclient.models.SearchAutocompleteRequest dataclass

Body of a synchronous autocomplete request against a SearchIndex. The autocomplete endpoint allowlists only query (restricted to prefix, match_phrase_prefix, or match_bool_prefix) and _source.

Represents a Synapse SearchAutocompleteRequest.

Source code in synapseclient/models/search_management.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
@dataclass
class SearchAutocompleteRequest:
    """Body of a synchronous autocomplete request against a SearchIndex. The
    autocomplete endpoint allowlists only `query` (restricted to
    [`prefix`](https://docs.opensearch.org/latest/query-dsl/term/prefix/),
    [`match_phrase_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase-prefix/),
    or [`match_bool_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-bool-prefix/))
    and `_source`.

    Represents a [Synapse SearchAutocompleteRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/table/SearchAutocompleteRequest.html).
    """

    search_index_id: Optional[str] = None
    """The ID of the SearchIndex entity to query."""

    query: Optional[Query] = None
    """Required. The top-level
    [Query][synapseclient.models.search_dsl.Query] DSL clause; restricted
    server-side to `prefix`, `match_phrase_prefix`, or
    `match_bool_prefix`."""

    source: Optional[SourceFilter] = None
    """Optional. [Source filter](https://docs.opensearch.org/latest/search-plugins/searching-data/retrieve-specific-fields/);
    same shape as `SearchQuery.source`. Serialized as `_source`."""

    def to_synapse_request(self) -> Dict[str, Any]:
        search_query = {
            "query": self.query,
            "_source": self.source,
        }
        delete_none_keys(search_query)
        body = {
            "searchIndexId": self.search_index_id,
            "searchQuery": search_query or None,
        }
        delete_none_keys(body)
        return body

Attributes

search_index_id class-attribute instance-attribute

search_index_id: Optional[str] = None

The ID of the SearchIndex entity to query.

query class-attribute instance-attribute

query: Optional[Query] = None

Required. The top-level Query DSL clause; restricted server-side to prefix, match_phrase_prefix, or match_bool_prefix.

source class-attribute instance-attribute

source: Optional[SourceFilter] = None

Optional. Source filter; same shape as SearchQuery.source. Serialized as _source.

synapseclient.models.SearchHit dataclass

A single matching document in a SearchQueryResults response.

Represents a Synapse SearchHit.

Source code in synapseclient/models/search_management.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
@dataclass
class SearchHit:
    """A single matching document in a SearchQueryResults response.

    Represents a [Synapse SearchHit](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/SearchHit.html).
    """

    row_id: Optional[int] = None
    """The row ID from the source table."""

    row_version: Optional[int] = None
    """The row version from the source table."""

    score: Optional[float] = None
    """The relevance score for this hit."""

    fields: Optional[List[SearchFieldValue]] = field(default_factory=list)
    """Column name/value pairs for the requested return fields."""

    highlights: Optional[List[SearchHighlight]] = field(default_factory=list)
    """Per-field highlight payloads, if highlight was requested."""

    def fill_from_dict(self, data: Dict[str, Any]) -> "Self":
        self.row_id = data.get("rowId", None)
        self.row_version = data.get("rowVersion", None)
        self.score = data.get("score", None)
        self.fields = [
            SearchFieldValue().fill_from_dict(f) for f in data.get("fields", []) or []
        ]
        self.highlights = [
            SearchHighlight().fill_from_dict(h)
            for h in data.get("highlights", []) or []
        ]
        return self

Attributes

row_id class-attribute instance-attribute

row_id: Optional[int] = None

The row ID from the source table.

row_version class-attribute instance-attribute

row_version: Optional[int] = None

The row version from the source table.

score class-attribute instance-attribute

score: Optional[float] = None

The relevance score for this hit.

fields class-attribute instance-attribute

fields: Optional[List[SearchFieldValue]] = field(default_factory=list)

Column name/value pairs for the requested return fields.

highlights class-attribute instance-attribute

highlights: Optional[List[SearchHighlight]] = field(default_factory=list)

Per-field highlight payloads, if highlight was requested.

synapseclient.models.SearchFieldValue dataclass

A name/value pair returned in a SearchHit's fields.

Represents a Synapse SearchFieldValue.

Source code in synapseclient/models/search_management.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
@dataclass
class SearchFieldValue:
    """A name/value pair returned in a SearchHit's `fields`.

    Represents a [Synapse SearchFieldValue](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/SearchFieldValue.html).
    """

    name: Optional[str] = None
    """The column name."""

    value: Optional[str] = None
    """The column value."""

    def fill_from_dict(self, data: Dict[str, Any]) -> "Self":
        self.name = data.get("name", None)
        self.value = data.get("value", None)
        return self

Attributes

name class-attribute instance-attribute

name: Optional[str] = None

The column name.

value class-attribute instance-attribute

value: Optional[str] = None

The column value.

synapseclient.models.SearchHighlight dataclass

A per-field highlight payload on a SearchHit.

Represents a Synapse SearchHighlight.

Source code in synapseclient/models/search_management.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
@dataclass
class SearchHighlight:
    """A per-field highlight payload on a SearchHit.

    Represents a [Synapse SearchHighlight](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/search/SearchHighlight.html).
    """

    name: Optional[str] = None
    """The column name."""

    snippets: Optional[List[str]] = field(default_factory=list)
    """Highlighted snippet fragments. Matched terms are wrapped in pre/post tags
    (default `<em>` / `</em>`)."""

    def fill_from_dict(self, data: Dict[str, Any]) -> "Self":
        self.name = data.get("name", None)
        self.snippets = data.get("snippets", []) or []
        return self

Attributes

name class-attribute instance-attribute

name: Optional[str] = None

The column name.

snippets class-attribute instance-attribute

snippets: Optional[List[str]] = field(default_factory=list)

Highlighted snippet fragments. Matched terms are wrapped in pre/post tags (default <em> / </em>).

OpenSearch query DSL

synapseclient.models.search_dsl.Query

Bases: TypedDict

A single OpenSearch query DSL clause. Exactly one of the keys below may be set -- the set key names the clause kind. See query vs. filter context and term-level vs. full-text queries.

The field-keyed leaf clauses (match, term, range, ...) are maps whose key is the column name and whose value is the per-field options object -- only the long form is accepted (e.g. {"match": {"title": {"query": "x"}}}, not the {"match": {"title": "x"}} shorthand). The compound clauses (bool, dis_max, ...) nest further Query DSL clauses recursively.

Source code in synapseclient/models/search_dsl.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
class Query(TypedDict, total=False):
    """A single [OpenSearch query DSL](https://docs.opensearch.org/latest/query-dsl/)
    clause. Exactly one of the keys below may be set -- the set key names the
    clause kind. See [query vs. filter context](https://docs.opensearch.org/latest/query-dsl/query-filter-context/)
    and [term-level vs. full-text queries](https://docs.opensearch.org/latest/query-dsl/term-vs-full-text/).

    The field-keyed leaf clauses (`match`, `term`, `range`, ...) are maps whose
    key is the column name and whose value is the per-field options object --
    only the long form is accepted (e.g. `{"match": {"title": {"query": "x"}}}`,
    not the `{"match": {"title": "x"}}` shorthand). The compound clauses
    (`bool`, `dis_max`, ...) nest further Query DSL clauses recursively.
    """

    match: Dict[str, MatchFieldOptions]
    """A [`match`](https://docs.opensearch.org/latest/query-dsl/full-text/match/)
    full-text clause. Map of column name to its match options."""

    match_phrase: Dict[str, MatchPhraseFieldOptions]
    """A [`match_phrase`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase/)
    clause. Map of column name to its phrase options."""

    match_phrase_prefix: Dict[str, MatchPhrasePrefixFieldOptions]
    """A [`match_phrase_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase-prefix/)
    clause. Map of column name to its options."""

    match_bool_prefix: Dict[str, MatchBoolPrefixFieldOptions]
    """A [`match_bool_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-bool-prefix/)
    clause. Map of column name to its options."""

    term: Dict[str, TermFieldOptions]
    """A [`term`](https://docs.opensearch.org/latest/query-dsl/term/term/)
    term-level clause. Map of column name to its term options."""

    range: Dict[str, RangeFieldOptions]
    """A [`range`](https://docs.opensearch.org/latest/query-dsl/term/range/)
    term-level clause. Map of column name to its range bounds."""

    prefix: Dict[str, PrefixFieldOptions]
    """A [`prefix`](https://docs.opensearch.org/latest/query-dsl/term/prefix/)
    term-level clause. Map of column name to its prefix options."""

    wildcard: Dict[str, WildcardFieldOptions]
    """A [`wildcard`](https://docs.opensearch.org/latest/query-dsl/term/wildcard/)
    term-level clause. Map of column name to its wildcard options."""

    fuzzy: Dict[str, FuzzyFieldOptions]
    """A [`fuzzy`](https://docs.opensearch.org/latest/query-dsl/term/fuzzy/)
    term-level clause. Map of column name to its fuzzy options."""

    terms: Dict[str, Any]
    """A [`terms`](https://docs.opensearch.org/latest/query-dsl/term/terms/)
    term-level clause (matches any of several exact values). Field-keyed:
    `{"terms": {"<column>": [v1, v2], "boost": 1.0}}`. The cross-index
    `terms`-lookup form is rejected. Untyped because the column name is itself a
    key alongside the fixed option keys, which a `TypedDict` cannot express; the
    same allowlist is enforced server-side."""

    exists: ExistsQuery
    """An [`exists`](https://docs.opensearch.org/latest/query-dsl/term/exists/)
    term-level clause."""

    multi_match: MultiMatchQuery
    """A [`multi_match`](https://docs.opensearch.org/latest/query-dsl/full-text/multi-match/)
    full-text clause."""

    simple_query_string: SimpleQueryStringQuery
    """A [`simple_query_string`](https://docs.opensearch.org/latest/query-dsl/full-text/simple-query-string/)
    full-text clause."""

    match_all: MatchAllQuery
    """A [`match_all`](https://docs.opensearch.org/latest/query-dsl/match-all/)
    clause."""

    bool: BoolQuery
    """A [`bool`](https://docs.opensearch.org/latest/query-dsl/compound/bool/)
    compound clause -- combines sub-clauses with boolean logic."""

    dis_max: DisMaxQuery
    """A [`dis_max`](https://docs.opensearch.org/latest/query-dsl/compound/disjunction-max/)
    compound clause."""

    constant_score: ConstantScoreQuery
    """A [`constant_score`](https://docs.opensearch.org/latest/query-dsl/compound/constant-score/)
    compound clause."""

    boosting: BoostingQuery
    """A [`boosting`](https://docs.opensearch.org/latest/query-dsl/compound/boosting/)
    compound clause."""

Attributes

match instance-attribute

A match full-text clause. Map of column name to its match options.

match_phrase instance-attribute

A match_phrase clause. Map of column name to its phrase options.

match_phrase_prefix instance-attribute

match_phrase_prefix: Dict[str, MatchPhrasePrefixFieldOptions]

A match_phrase_prefix clause. Map of column name to its options.

match_bool_prefix instance-attribute

match_bool_prefix: Dict[str, MatchBoolPrefixFieldOptions]

A match_bool_prefix clause. Map of column name to its options.

term instance-attribute

A term term-level clause. Map of column name to its term options.

range instance-attribute

A range term-level clause. Map of column name to its range bounds.

prefix instance-attribute

A prefix term-level clause. Map of column name to its prefix options.

wildcard instance-attribute

A wildcard term-level clause. Map of column name to its wildcard options.

fuzzy instance-attribute

A fuzzy term-level clause. Map of column name to its fuzzy options.

terms instance-attribute

terms: Dict[str, Any]

A terms term-level clause (matches any of several exact values). Field-keyed: {"terms": {"<column>": [v1, v2], "boost": 1.0}}. The cross-index terms-lookup form is rejected. Untyped because the column name is itself a key alongside the fixed option keys, which a TypedDict cannot express; the same allowlist is enforced server-side.

exists instance-attribute

exists: ExistsQuery

An exists term-level clause.

multi_match instance-attribute

multi_match: MultiMatchQuery

A multi_match full-text clause.

simple_query_string instance-attribute

simple_query_string: SimpleQueryStringQuery

A simple_query_string full-text clause.

match_all instance-attribute

match_all: MatchAllQuery

A match_all clause.

bool instance-attribute

bool: BoolQuery

A bool compound clause -- combines sub-clauses with boolean logic.

dis_max instance-attribute

dis_max: DisMaxQuery

A dis_max compound clause.

constant_score instance-attribute

constant_score: ConstantScoreQuery

A constant_score compound clause.

boosting instance-attribute

boosting: BoostingQuery

A boosting compound clause.

Leaf clause field options

synapseclient.models.search_dsl.MatchFieldOptions

Bases: ClauseScoringOptions, FuzzyMatchOptions, MinimumShouldMatchOption, ZeroTermsQueryOption

Per-field options for a match full-text clause. Carried as the value of the field-keyed match map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
class MatchFieldOptions(
    ClauseScoringOptions,
    FuzzyMatchOptions,
    MinimumShouldMatchOption,
    ZeroTermsQueryOption,
    total=False,
):
    """Per-field options for a [`match`](https://docs.opensearch.org/latest/query-dsl/full-text/match/)
    full-text clause. Carried as the value of the field-keyed `match` map (the
    map key is the column name)."""

    query: ScalarValue
    """Required. The text (or scalar value on a non-text column) to match. A
    string, number, or boolean depending on the target column type."""

    operator: str
    """Optional. Boolean logic used to combine the analyzed query terms: `or`
    (default) or `and`."""

    analyzer: str
    """Optional. Analyzer used to tokenize the query text. Defaults to the
    field's search analyzer."""

    max_expansions: int
    """Optional. Maximum number of terms the fuzzy expansion will generate."""

    cutoff_frequency: float
    """Optional. Term-frequency threshold above which terms are treated as
    low-importance."""

    auto_generate_synonyms_phrase_query: bool
    """Optional. Whether to auto-generate phrase queries for multi-term
    synonyms. Default `true`."""

    lenient: bool
    """Optional. When `true`, format-based errors (e.g. a text value against a
    numeric field) are ignored."""

Attributes

query instance-attribute

query: ScalarValue

Required. The text (or scalar value on a non-text column) to match. A string, number, or boolean depending on the target column type.

operator instance-attribute

operator: str

Optional. Boolean logic used to combine the analyzed query terms: or (default) or and.

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the query text. Defaults to the field's search analyzer.

max_expansions instance-attribute

max_expansions: int

Optional. Maximum number of terms the fuzzy expansion will generate.

cutoff_frequency instance-attribute

cutoff_frequency: float

Optional. Term-frequency threshold above which terms are treated as low-importance.

auto_generate_synonyms_phrase_query instance-attribute

auto_generate_synonyms_phrase_query: bool

Optional. Whether to auto-generate phrase queries for multi-term synonyms. Default true.

lenient instance-attribute

lenient: bool

Optional. When true, format-based errors (e.g. a text value against a numeric field) are ignored.

synapseclient.models.search_dsl.MatchPhraseFieldOptions

Bases: ClauseScoringOptions, ZeroTermsQueryOption

Per-field options for a match_phrase clause. Carried as the value of the field-keyed match_phrase map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class MatchPhraseFieldOptions(ClauseScoringOptions, ZeroTermsQueryOption, total=False):
    """Per-field options for a [`match_phrase`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase/)
    clause. Carried as the value of the field-keyed `match_phrase` map (the map
    key is the column name)."""

    query: ScalarValue
    """Required. The phrase to match. A string (or scalar value on a non-text
    column)."""

    analyzer: str
    """Optional. Analyzer used to tokenize the phrase. Defaults to the field's
    search analyzer."""

    slop: int
    """Optional. Number of positions allowed between matching terms. Default
    `0` (exact phrase)."""

Attributes

query instance-attribute

query: ScalarValue

Required. The phrase to match. A string (or scalar value on a non-text column).

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the phrase. Defaults to the field's search analyzer.

slop instance-attribute

slop: int

Optional. Number of positions allowed between matching terms. Default 0 (exact phrase).

synapseclient.models.search_dsl.MatchPhrasePrefixFieldOptions

Bases: ClauseScoringOptions, ZeroTermsQueryOption

Per-field options for a match_phrase_prefix clause. Carried as the value of the field-keyed match_phrase_prefix map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
class MatchPhrasePrefixFieldOptions(
    ClauseScoringOptions, ZeroTermsQueryOption, total=False
):
    """Per-field options for a [`match_phrase_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-phrase-prefix/)
    clause. Carried as the value of the field-keyed `match_phrase_prefix` map
    (the map key is the column name)."""

    query: ScalarValue
    """Required. The phrase whose last term is treated as a prefix. A
    string."""

    analyzer: str
    """Optional. Analyzer used to tokenize the phrase. Defaults to the field's
    search analyzer."""

    slop: int
    """Optional. Number of positions allowed between matching terms. Default
    `0`."""

    max_expansions: int
    """Optional. Maximum number of terms the last (prefix) term expands into.
    Default `50`."""

Attributes

query instance-attribute

query: ScalarValue

Required. The phrase whose last term is treated as a prefix. A string.

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the phrase. Defaults to the field's search analyzer.

slop instance-attribute

slop: int

Optional. Number of positions allowed between matching terms. Default 0.

max_expansions instance-attribute

max_expansions: int

Optional. Maximum number of terms the last (prefix) term expands into. Default 50.

synapseclient.models.search_dsl.MatchBoolPrefixFieldOptions

Bases: ClauseScoringOptions, FuzzyMatchOptions, MinimumShouldMatchOption

Per-field options for a match_bool_prefix clause. Carried as the value of the field-keyed match_bool_prefix map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class MatchBoolPrefixFieldOptions(
    ClauseScoringOptions, FuzzyMatchOptions, MinimumShouldMatchOption, total=False
):
    """Per-field options for a [`match_bool_prefix`](https://docs.opensearch.org/latest/query-dsl/full-text/match-bool-prefix/)
    clause. Carried as the value of the field-keyed `match_bool_prefix` map
    (the map key is the column name)."""

    query: ScalarValue
    """Required. The text whose terms are matched, with the final term treated
    as a prefix. A string."""

    operator: str
    """Optional. Boolean logic used to combine the analyzed terms: `or`
    (default) or `and`."""

    analyzer: str
    """Optional. Analyzer used to tokenize the query text. Defaults to the
    field's search analyzer."""

    max_expansions: int
    """Optional. Maximum number of terms the final (prefix) term expands into.
    Default `50`."""

Attributes

query instance-attribute

query: ScalarValue

Required. The text whose terms are matched, with the final term treated as a prefix. A string.

operator instance-attribute

operator: str

Optional. Boolean logic used to combine the analyzed terms: or (default) or and.

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the query text. Defaults to the field's search analyzer.

max_expansions instance-attribute

max_expansions: int

Optional. Maximum number of terms the final (prefix) term expands into. Default 50.

synapseclient.models.search_dsl.TermFieldOptions

Bases: ClauseScoringOptions

Per-field options for a term term-level clause (exact, non-analyzed match). Carried as the value of the field-keyed term map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
196
197
198
199
200
201
202
203
204
205
206
207
class TermFieldOptions(ClauseScoringOptions, total=False):
    """Per-field options for a [`term`](https://docs.opensearch.org/latest/query-dsl/term/term/)
    term-level clause (exact, non-analyzed match). Carried as the value of the
    field-keyed `term` map (the map key is the column name)."""

    value: ScalarValue
    """Required. The exact value to match. A string, number, boolean, or date
    depending on the target column type."""

    case_insensitive: bool
    """Optional. When `true`, matches the value regardless of case. Default
    `false`."""

Attributes

value instance-attribute

value: ScalarValue

Required. The exact value to match. A string, number, boolean, or date depending on the target column type.

case_insensitive instance-attribute

case_insensitive: bool

Optional. When true, matches the value regardless of case. Default false.

synapseclient.models.search_dsl.RangeFieldOptions

Bases: ClauseScoringOptions

Per-field options for a range term-level clause. Carried as the value of the field-keyed range map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
class RangeFieldOptions(ClauseScoringOptions, total=False):
    """Per-field options for a [`range`](https://docs.opensearch.org/latest/query-dsl/term/range/)
    term-level clause. Carried as the value of the field-keyed `range` map (the
    map key is the column name)."""

    gte: ScalarValue
    """Optional. Greater-than-or-equal-to bound. A number or date string, per
    the target column type."""

    gt: ScalarValue
    """Optional. Greater-than bound."""

    lte: ScalarValue
    """Optional. Less-than-or-equal-to bound."""

    lt: ScalarValue
    """Optional. Less-than bound."""

    format: str
    """Optional. Date format used to parse the bound values on a date
    column."""

    relation: str
    """Optional. How the range relates to range-typed field values:
    `INTERSECTS` (default), `CONTAINS`, or `WITHIN`."""

    time_zone: str
    """Optional. UTC offset or IANA zone used to interpret date bounds."""

Attributes

gte instance-attribute

gte: ScalarValue

Optional. Greater-than-or-equal-to bound. A number or date string, per the target column type.

gt instance-attribute

gt: ScalarValue

Optional. Greater-than bound.

lte instance-attribute

lte: ScalarValue

Optional. Less-than-or-equal-to bound.

lt instance-attribute

lt: ScalarValue

Optional. Less-than bound.

format instance-attribute

format: str

Optional. Date format used to parse the bound values on a date column.

relation instance-attribute

relation: str

Optional. How the range relates to range-typed field values: INTERSECTS (default), CONTAINS, or WITHIN.

time_zone instance-attribute

time_zone: str

Optional. UTC offset or IANA zone used to interpret date bounds.

synapseclient.models.search_dsl.PrefixFieldOptions

Bases: ClauseScoringOptions

Per-field options for a prefix term-level clause. Carried as the value of the field-keyed prefix map (the map key is the column name). A leading * or ? in value is rejected (it forces a full index scan).

Source code in synapseclient/models/search_dsl.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class PrefixFieldOptions(ClauseScoringOptions, total=False):
    """Per-field options for a [`prefix`](https://docs.opensearch.org/latest/query-dsl/term/prefix/)
    term-level clause. Carried as the value of the field-keyed `prefix` map
    (the map key is the column name). A leading `*` or `?` in `value` is
    rejected (it forces a full index scan)."""

    value: ScalarValue
    """Required. The prefix the indexed term must start with. A string (or
    scalar value on a non-text column)."""

    case_insensitive: bool
    """Optional. When `true`, matches the prefix regardless of case. Default
    `false`."""

    rewrite: str
    """Optional. How the multi-term query is rewritten internally."""

Attributes

value instance-attribute

value: ScalarValue

Required. The prefix the indexed term must start with. A string (or scalar value on a non-text column).

case_insensitive instance-attribute

case_insensitive: bool

Optional. When true, matches the prefix regardless of case. Default false.

rewrite instance-attribute

rewrite: str

Optional. How the multi-term query is rewritten internally.

synapseclient.models.search_dsl.WildcardFieldOptions

Bases: ClauseScoringOptions

Per-field options for a wildcard term-level clause. Carried as the value of the field-keyed wildcard map (the map key is the column name). A leading * or ? in the pattern is rejected (it forces a full index scan).

Source code in synapseclient/models/search_dsl.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
class WildcardFieldOptions(ClauseScoringOptions, total=False):
    """Per-field options for a [`wildcard`](https://docs.opensearch.org/latest/query-dsl/term/wildcard/)
    term-level clause. Carried as the value of the field-keyed `wildcard` map
    (the map key is the column name). A leading `*` or `?` in the pattern is
    rejected (it forces a full index scan)."""

    value: ScalarValue
    """Optional. The wildcard pattern (`*` matches any sequence, `?` matches a
    single character). A string. Either `value` or `wildcard` supplies the
    pattern."""

    wildcard: ScalarValue
    """Optional. Alias for `value` -- the wildcard pattern. A string."""

    case_insensitive: bool
    """Optional. When `true`, matches the pattern regardless of case. Default
    `false`."""

    rewrite: str
    """Optional. How the multi-term query is rewritten internally."""

Attributes

value instance-attribute

value: ScalarValue

Optional. The wildcard pattern (* matches any sequence, ? matches a single character). A string. Either value or wildcard supplies the pattern.

wildcard instance-attribute

wildcard: ScalarValue

Optional. Alias for value -- the wildcard pattern. A string.

case_insensitive instance-attribute

case_insensitive: bool

Optional. When true, matches the pattern regardless of case. Default false.

rewrite instance-attribute

rewrite: str

Optional. How the multi-term query is rewritten internally.

synapseclient.models.search_dsl.FuzzyFieldOptions

Bases: ClauseScoringOptions

Per-field options for a fuzzy term-level clause. Carried as the value of the field-keyed fuzzy map (the map key is the column name).

Source code in synapseclient/models/search_dsl.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
class FuzzyFieldOptions(ClauseScoringOptions, total=False):
    """Per-field options for a [`fuzzy`](https://docs.opensearch.org/latest/query-dsl/term/fuzzy/)
    term-level clause. Carried as the value of the field-keyed `fuzzy` map (the
    map key is the column name)."""

    value: ScalarValue
    """Required. The term to match within the allowed edit distance. A string
    (or scalar value on a non-text column)."""

    fuzziness: Union[int, str]
    """Optional. Allowed [edit distance](https://docs.opensearch.org/latest/query-dsl/term/fuzzy/):
    an integer or `AUTO`."""

    max_expansions: int
    """Optional. Maximum number of terms the fuzzy expansion will generate.
    Default `50`."""

    prefix_length: int
    """Optional. Number of leading characters left unchanged when fuzzy
    matching."""

    transpositions: bool
    """Optional. Whether to count transpositions (ab -> ba) as a single edit.
    Default `true`."""

    rewrite: str
    """Optional. How the multi-term query is rewritten internally."""

Attributes

value instance-attribute

value: ScalarValue

Required. The term to match within the allowed edit distance. A string (or scalar value on a non-text column).

fuzziness instance-attribute

fuzziness: Union[int, str]

Optional. Allowed edit distance: an integer or AUTO.

max_expansions instance-attribute

max_expansions: int

Optional. Maximum number of terms the fuzzy expansion will generate. Default 50.

prefix_length instance-attribute

prefix_length: int

Optional. Number of leading characters left unchanged when fuzzy matching.

transpositions instance-attribute

transpositions: bool

Optional. Whether to count transpositions (ab -> ba) as a single edit. Default true.

rewrite instance-attribute

rewrite: str

Optional. How the multi-term query is rewritten internally.

synapseclient.models.search_dsl.ExistsQuery

Bases: ClauseScoringOptions

An exists term-level clause. Matches documents that have any non-null value for the given column.

Source code in synapseclient/models/search_dsl.py
309
310
311
312
313
314
315
class ExistsQuery(ClauseScoringOptions, total=False):
    """An [`exists`](https://docs.opensearch.org/latest/query-dsl/term/exists/)
    term-level clause. Matches documents that have any non-null value for the
    given column."""

    field: str
    """Required. The column that must have a value."""

Attributes

field instance-attribute

field: str

Required. The column that must have a value.

synapseclient.models.search_dsl.MultiMatchQuery

Bases: ClauseScoringOptions, FuzzyMatchOptions, MinimumShouldMatchOption, ZeroTermsQueryOption

A multi_match full-text clause -- a match run across several columns at once.

Source code in synapseclient/models/search_dsl.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class MultiMatchQuery(
    ClauseScoringOptions,
    FuzzyMatchOptions,
    MinimumShouldMatchOption,
    ZeroTermsQueryOption,
    total=False,
):
    """A [`multi_match`](https://docs.opensearch.org/latest/query-dsl/full-text/multi-match/)
    full-text clause -- a `match` run across several columns at once."""

    query: ScalarValue
    """Required. The text to match across the listed columns. A string."""

    fields: List[str]
    """Required. The columns to search. Each entry may carry a `^boost` suffix
    (e.g. `title^2`)."""

    type: str
    """Optional. How the per-field matches are combined: `best_fields`
    (default), `most_fields`, `cross_fields`, `phrase`, `phrase_prefix`, or
    `bool_prefix`."""

    operator: str
    """Optional. Boolean logic used to combine the analyzed terms: `or`
    (default) or `and`."""

    tie_breaker: float
    """Optional. Weight (0-1) applied to non-best field scores in
    `best_fields` / `cross_fields`."""

    analyzer: str
    """Optional. Analyzer used to tokenize the query text. Defaults to each
    field's search analyzer."""

    max_expansions: int
    """Optional. Maximum number of terms a fuzzy / prefix expansion will
    generate. Default `50`."""

    slop: int
    """Optional. Number of positions allowed between matching terms for the
    phrase types."""

    cutoff_frequency: float
    """Optional. Term-frequency threshold above which terms are treated as
    low-importance."""

    auto_generate_synonyms_phrase_query: bool
    """Optional. Whether to auto-generate phrase queries for multi-term
    synonyms. Default `true`."""

    lenient: bool
    """Optional. When `true`, format-based errors are ignored."""

Attributes

query instance-attribute

query: ScalarValue

Required. The text to match across the listed columns. A string.

fields instance-attribute

fields: List[str]

Required. The columns to search. Each entry may carry a ^boost suffix (e.g. title^2).

type instance-attribute

type: str

Optional. How the per-field matches are combined: best_fields (default), most_fields, cross_fields, phrase, phrase_prefix, or bool_prefix.

operator instance-attribute

operator: str

Optional. Boolean logic used to combine the analyzed terms: or (default) or and.

tie_breaker instance-attribute

tie_breaker: float

Optional. Weight (0-1) applied to non-best field scores in best_fields / cross_fields.

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the query text. Defaults to each field's search analyzer.

max_expansions instance-attribute

max_expansions: int

Optional. Maximum number of terms a fuzzy / prefix expansion will generate. Default 50.

slop instance-attribute

slop: int

Optional. Number of positions allowed between matching terms for the phrase types.

cutoff_frequency instance-attribute

cutoff_frequency: float

Optional. Term-frequency threshold above which terms are treated as low-importance.

auto_generate_synonyms_phrase_query instance-attribute

auto_generate_synonyms_phrase_query: bool

Optional. Whether to auto-generate phrase queries for multi-term synonyms. Default true.

lenient instance-attribute

lenient: bool

Optional. When true, format-based errors are ignored.

synapseclient.models.search_dsl.SimpleQueryStringQuery

Bases: ClauseScoringOptions, MinimumShouldMatchOption

A simple_query_string full-text clause -- a compact mini-DSL (+, |, -, ", *, ()) parsed leniently across the listed columns.

Source code in synapseclient/models/search_dsl.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
class SimpleQueryStringQuery(
    ClauseScoringOptions, MinimumShouldMatchOption, total=False
):
    """A [`simple_query_string`](https://docs.opensearch.org/latest/query-dsl/full-text/simple-query-string/)
    full-text clause -- a compact mini-DSL (`+`, `|`, `-`, `"`, `*`, `()`)
    parsed leniently across the listed columns."""

    query: str
    """Required. The simple-query-string expression."""

    fields: List[str]
    """Optional. The columns to search. Each entry may carry a `^boost`
    suffix. Defaults to the index's default search fields."""

    default_operator: str
    """Optional. Boolean logic used between terms when no explicit operator is
    given: `or` (default) or `and`."""

    flags: str
    """Optional. Pipe-delimited list of enabled syntax features (e.g.
    `AND|OR|PREFIX`), or `ALL` / `NONE`."""

    analyzer: str
    """Optional. Analyzer used to tokenize the query text. Defaults to each
    field's search analyzer."""

    analyze_wildcard: bool
    """Optional. Whether to analyze wildcard terms. Default `false`. A leading
    wildcard with this enabled is rejected (it forces a full index scan)."""

    auto_generate_synonyms_phrase_query: bool
    """Optional. Whether to auto-generate phrase queries for multi-term
    synonyms. Default `true`."""

    fuzzy_max_expansions: int
    """Optional. Maximum number of terms a fuzzy expansion will generate.
    Default `50`."""

    fuzzy_prefix_length: int
    """Optional. Number of leading characters left unchanged when fuzzy
    matching."""

    fuzzy_transpositions: bool
    """Optional. Whether to count transpositions (ab -> ba) as a single edit.
    Default `true`."""

    lenient: bool
    """Optional. When `true`, format-based errors are ignored."""

    quote_field_suffix: str
    """Optional. Suffix appended to field names for quoted (exact-phrase)
    portions of the query."""

Attributes

query instance-attribute

query: str

Required. The simple-query-string expression.

fields instance-attribute

fields: List[str]

Optional. The columns to search. Each entry may carry a ^boost suffix. Defaults to the index's default search fields.

default_operator instance-attribute

default_operator: str

Optional. Boolean logic used between terms when no explicit operator is given: or (default) or and.

flags instance-attribute

flags: str

Optional. Pipe-delimited list of enabled syntax features (e.g. AND|OR|PREFIX), or ALL / NONE.

analyzer instance-attribute

analyzer: str

Optional. Analyzer used to tokenize the query text. Defaults to each field's search analyzer.

analyze_wildcard instance-attribute

analyze_wildcard: bool

Optional. Whether to analyze wildcard terms. Default false. A leading wildcard with this enabled is rejected (it forces a full index scan).

auto_generate_synonyms_phrase_query instance-attribute

auto_generate_synonyms_phrase_query: bool

Optional. Whether to auto-generate phrase queries for multi-term synonyms. Default true.

fuzzy_max_expansions instance-attribute

fuzzy_max_expansions: int

Optional. Maximum number of terms a fuzzy expansion will generate. Default 50.

fuzzy_prefix_length instance-attribute

fuzzy_prefix_length: int

Optional. Number of leading characters left unchanged when fuzzy matching.

fuzzy_transpositions instance-attribute

fuzzy_transpositions: bool

Optional. Whether to count transpositions (ab -> ba) as a single edit. Default true.

lenient instance-attribute

lenient: bool

Optional. When true, format-based errors are ignored.

quote_field_suffix instance-attribute

quote_field_suffix: str

Optional. Suffix appended to field names for quoted (exact-phrase) portions of the query.

synapseclient.models.search_dsl.MatchAllQuery

Bases: ClauseScoringOptions

A match_all clause. Matches every document. Use {"match_all": {}} to match all documents.

Source code in synapseclient/models/search_dsl.py
426
427
428
429
class MatchAllQuery(ClauseScoringOptions, total=False):
    """A [`match_all`](https://docs.opensearch.org/latest/query-dsl/match-all/)
    clause. Matches every document. Use `{"match_all": {}}` to match all
    documents."""

Compound clauses

synapseclient.models.search_dsl.BoolQuery

Bases: ClauseScoringOptions

A bool compound clause -- combines sub-clauses with boolean logic.

Source code in synapseclient/models/search_dsl.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
class BoolQuery(ClauseScoringOptions, total=False):
    """A [`bool`](https://docs.opensearch.org/latest/query-dsl/compound/bool/)
    compound clause -- combines sub-clauses with boolean logic."""

    must: List["Query"]
    """Sub-clauses that must all match (scored). Logical AND."""

    should: List["Query"]
    """Sub-clauses that should match (scored). See `minimum_should_match`."""

    must_not: List["Query"]
    """Sub-clauses that must not match (filter context, not scored)."""

    filter: List["Query"]
    """Sub-clauses that must all match in
    [filter context](https://docs.opensearch.org/latest/query-dsl/query-filter-context/)
    (not scored)."""

    minimum_should_match: Union[int, str]
    """Optional. How many `should` clauses must match. An integer or a
    [percentage / formula string](https://docs.opensearch.org/latest/query-dsl/minimum-should-match/)."""

    adjust_pure_negative: bool
    """Optional. Whether to automatically add a `match_all` when only negative
    clauses are present. Default `true`."""

Attributes

must instance-attribute

must: List[Query]

Sub-clauses that must all match (scored). Logical AND.

should instance-attribute

should: List[Query]

Sub-clauses that should match (scored). See minimum_should_match.

must_not instance-attribute

must_not: List[Query]

Sub-clauses that must not match (filter context, not scored).

filter instance-attribute

filter: List[Query]

Sub-clauses that must all match in filter context (not scored).

minimum_should_match instance-attribute

minimum_should_match: Union[int, str]

Optional. How many should clauses must match. An integer or a percentage / formula string.

adjust_pure_negative instance-attribute

adjust_pure_negative: bool

Optional. Whether to automatically add a match_all when only negative clauses are present. Default true.

synapseclient.models.search_dsl.DisMaxQuery

Bases: ClauseScoringOptions

A dis_max compound clause. A document matches if any sub-clause matches; its score is the best single sub-clause score plus tie_breaker times the rest.

Source code in synapseclient/models/search_dsl.py
459
460
461
462
463
464
465
466
467
468
469
class DisMaxQuery(ClauseScoringOptions, total=False):
    """A [`dis_max`](https://docs.opensearch.org/latest/query-dsl/compound/disjunction-max/)
    compound clause. A document matches if any sub-clause matches; its score is
    the best single sub-clause score plus `tie_breaker` times the rest."""

    queries: List["Query"]
    """Required. The candidate clauses."""

    tie_breaker: float
    """Optional. Weight (0-1) applied to the scores of the non-best matching
    clauses. Default `0.0`."""

Attributes

queries instance-attribute

queries: List[Query]

Required. The candidate clauses.

tie_breaker instance-attribute

tie_breaker: float

Optional. Weight (0-1) applied to the scores of the non-best matching clauses. Default 0.0.

synapseclient.models.search_dsl.ConstantScoreQuery

Bases: ClauseScoringOptions

A constant_score compound clause. Wraps a filter and assigns every matching document the same score (boost).

Source code in synapseclient/models/search_dsl.py
472
473
474
475
476
477
478
479
class ConstantScoreQuery(ClauseScoringOptions, total=False):
    """A [`constant_score`](https://docs.opensearch.org/latest/query-dsl/compound/constant-score/)
    compound clause. Wraps a filter and assigns every matching document the
    same score (`boost`)."""

    filter: "Query"
    """Required. The clause evaluated in
    [filter context](https://docs.opensearch.org/latest/query-dsl/query-filter-context/)."""

Attributes

filter instance-attribute

filter: Query

Required. The clause evaluated in filter context.

synapseclient.models.search_dsl.BoostingQuery

Bases: ClauseScoringOptions

A boosting compound clause. Returns documents matching positive, demoting those that also match negative by negative_boost.

Source code in synapseclient/models/search_dsl.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
class BoostingQuery(ClauseScoringOptions, total=False):
    """A [`boosting`](https://docs.opensearch.org/latest/query-dsl/compound/boosting/)
    compound clause. Returns documents matching `positive`, demoting those that
    also match `negative` by `negative_boost`."""

    positive: "Query"
    """Required. The clause documents must match."""

    negative: "Query"
    """Required. The clause whose matches are demoted."""

    negative_boost: float
    """Required. Multiplier (0-1) applied to the score of documents that also
    match `negative`."""

Attributes

positive instance-attribute

positive: Query

Required. The clause documents must match.

negative instance-attribute

negative: Query

Required. The clause whose matches are demoted.

negative_boost instance-attribute

negative_boost: float

Required. Multiplier (0-1) applied to the score of documents that also match negative.

Shared per-field option mixins

synapseclient.models.search_dsl.ClauseScoringOptions

Bases: TypedDict

Scoring options shared by the OpenSearch query clauses: a relevance boost and a _name label.

Source code in synapseclient/models/search_dsl.py
41
42
43
44
45
46
47
48
49
50
class ClauseScoringOptions(TypedDict, total=False):
    """Scoring options shared by the OpenSearch query clauses: a relevance
    `boost` and a `_name` label."""

    boost: float
    """Optional. Multiplier for the relevance score of this clause.
    Default `1.0`."""

    _name: str
    """Optional. Label echoed back in matched-queries metadata."""

Attributes

boost instance-attribute

boost: float

Optional. Multiplier for the relevance score of this clause. Default 1.0.

synapseclient.models.search_dsl.FuzzyMatchOptions

Bases: TypedDict

Fuzzy-matching parameters shared by the analyzed full-text match clauses (match, match_bool_prefix, multi_match).

Source code in synapseclient/models/search_dsl.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class FuzzyMatchOptions(TypedDict, total=False):
    """Fuzzy-matching parameters shared by the analyzed full-text match clauses
    (`match`, `match_bool_prefix`, `multi_match`)."""

    fuzziness: Union[int, str]
    """Optional. Allowed [edit distance](https://docs.opensearch.org/latest/query-dsl/term/fuzzy/):
    an integer or `AUTO`."""

    fuzzy_rewrite: str
    """Optional. How the fuzzy query is rewritten internally."""

    fuzzy_transpositions: bool
    """Optional. Whether to count transpositions (ab -> ba) as a single edit.
    Default `true`."""

    prefix_length: int
    """Optional. Number of leading characters left unchanged when fuzzy
    matching."""

Attributes

fuzziness instance-attribute

fuzziness: Union[int, str]

Optional. Allowed edit distance: an integer or AUTO.

fuzzy_rewrite instance-attribute

fuzzy_rewrite: str

Optional. How the fuzzy query is rewritten internally.

fuzzy_transpositions instance-attribute

fuzzy_transpositions: bool

Optional. Whether to count transpositions (ab -> ba) as a single edit. Default true.

prefix_length instance-attribute

prefix_length: int

Optional. Number of leading characters left unchanged when fuzzy matching.

synapseclient.models.search_dsl.MinimumShouldMatchOption

Bases: TypedDict

The minimum-should-match option shared by the analyzed full-text match clauses.

Source code in synapseclient/models/search_dsl.py
73
74
75
76
77
78
79
class MinimumShouldMatchOption(TypedDict, total=False):
    """The minimum-should-match option shared by the analyzed full-text match
    clauses."""

    minimum_should_match: Union[int, str]
    """Optional. [Minimum number of terms](https://docs.opensearch.org/latest/query-dsl/minimum-should-match/)
    a document must match. An integer or a percentage / formula string."""

Attributes

minimum_should_match instance-attribute

minimum_should_match: Union[int, str]

Optional. Minimum number of terms a document must match. An integer or a percentage / formula string.

synapseclient.models.search_dsl.ZeroTermsQueryOption

Bases: TypedDict

The zero-terms-query behavior shared by the analyzed full-text match clauses.

Source code in synapseclient/models/search_dsl.py
82
83
84
85
86
87
88
class ZeroTermsQueryOption(TypedDict, total=False):
    """The zero-terms-query behavior shared by the analyzed full-text match
    clauses."""

    zero_terms_query: str
    """Optional. Behavior when the analyzer removes all tokens: `none`
    (default) or `all`."""

Attributes

zero_terms_query instance-attribute

zero_terms_query: str

Optional. Behavior when the analyzer removes all tokens: none (default) or all.

Aggregations

synapseclient.models.search_dsl.Aggregation

Bases: TypedDict

A single OpenSearch aggregation definition. Exactly one of the aggregation-kind keys below may be set; aggregations may additionally carry nested sub-aggregations.

The filter and filters kinds wrap a Query; that query is validated identically to the top-level query and is scoped by it, so a filter aggregation never counts documents outside the top-level query.

Source code in synapseclient/models/search_dsl.py
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
class Aggregation(TypedDict, total=False):
    """A single [OpenSearch aggregation](https://docs.opensearch.org/latest/aggregations/)
    definition. Exactly one of the aggregation-kind keys below may be set;
    `aggregations` may additionally carry nested sub-aggregations.

    The `filter` and `filters` kinds wrap a
    [Query][synapseclient.models.search_dsl.Query]; that query is validated
    identically to the top-level `query` and is scoped by it, so a `filter`
    aggregation never counts documents outside the top-level query.
    """

    terms: TermsAggregation
    """A [`terms`](https://docs.opensearch.org/latest/aggregations/bucket/terms/)
    bucket aggregation."""

    histogram: HistogramAggregation
    """A [`histogram`](https://docs.opensearch.org/latest/aggregations/bucket/histogram/)
    bucket aggregation."""

    date_histogram: DateHistogramAggregation
    """A [`date_histogram`](https://docs.opensearch.org/latest/aggregations/bucket/date-histogram/)
    bucket aggregation."""

    range: RangeAggregation
    """A [`range`](https://docs.opensearch.org/latest/aggregations/bucket/range/)
    bucket aggregation."""

    date_range: DateRangeAggregation
    """A [`date_range`](https://docs.opensearch.org/latest/aggregations/bucket/date-range/)
    bucket aggregation."""

    missing: MissingAggregation
    """A [`missing`](https://docs.opensearch.org/latest/aggregations/bucket/missing/)
    bucket aggregation."""

    min: MinAggregation
    """A [`min`](https://docs.opensearch.org/latest/aggregations/metric/minimum/)
    metric aggregation."""

    max: MaxAggregation
    """A [`max`](https://docs.opensearch.org/latest/aggregations/metric/maximum/)
    metric aggregation."""

    avg: AvgAggregation
    """An [`avg`](https://docs.opensearch.org/latest/aggregations/metric/average/)
    metric aggregation."""

    sum: SumAggregation
    """A [`sum`](https://docs.opensearch.org/latest/aggregations/metric/sum/)
    metric aggregation."""

    stats: StatsAggregation
    """A [`stats`](https://docs.opensearch.org/latest/aggregations/metric/stats/)
    metric aggregation."""

    extended_stats: ExtendedStatsAggregation
    """An [`extended_stats`](https://docs.opensearch.org/latest/aggregations/metric/extended-stats/)
    metric aggregation."""

    value_count: ValueCountAggregation
    """A [`value_count`](https://docs.opensearch.org/latest/aggregations/metric/value-count/)
    metric aggregation."""

    cardinality: CardinalityAggregation
    """A [`cardinality`](https://docs.opensearch.org/latest/aggregations/metric/cardinality/)
    metric aggregation."""

    filter: Query
    """A [`filter`](https://docs.opensearch.org/latest/aggregations/bucket/filter/)
    single-bucket aggregation. The body is a
    [Query][synapseclient.models.search_dsl.Query] -- validated like the
    top-level `query` -- that narrows the documents the nested `aggregations`
    see, within the top-level query scope."""

    filters: FiltersAggregation
    """A [`filters`](https://docs.opensearch.org/latest/aggregations/bucket/filters/)
    multi-bucket aggregation -- one named bucket per query."""

    aggregations: Dict[str, "Aggregation"]
    """Optional. Nested sub-aggregations, keyed by caller-chosen name. Bucket
    aggregations compute these once per bucket."""

Attributes

terms instance-attribute

A terms bucket aggregation.

histogram instance-attribute

A histogram bucket aggregation.

date_histogram instance-attribute

date_histogram: DateHistogramAggregation

A date_histogram bucket aggregation.

range instance-attribute

A range bucket aggregation.

date_range instance-attribute

A date_range bucket aggregation.

missing instance-attribute

A missing bucket aggregation.

min instance-attribute

A min metric aggregation.

max instance-attribute

A max metric aggregation.

avg instance-attribute

An avg metric aggregation.

sum instance-attribute

A sum metric aggregation.

stats instance-attribute

A stats metric aggregation.

extended_stats instance-attribute

extended_stats: ExtendedStatsAggregation

An extended_stats metric aggregation.

value_count instance-attribute

value_count: ValueCountAggregation

A value_count metric aggregation.

cardinality instance-attribute

A cardinality metric aggregation.

filter instance-attribute

filter: Query

A filter single-bucket aggregation. The body is a Query -- validated like the top-level query -- that narrows the documents the nested aggregations see, within the top-level query scope.

filters instance-attribute

A filters multi-bucket aggregation -- one named bucket per query.

aggregations instance-attribute

aggregations: Dict[str, Aggregation]

Optional. Nested sub-aggregations, keyed by caller-chosen name. Bucket aggregations compute these once per bucket.

synapseclient.models.search_dsl.TermsAggregation

Bases: TypedDict

A terms bucket aggregation -- one bucket per distinct value of field.

Source code in synapseclient/models/search_dsl.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
class TermsAggregation(TypedDict, total=False):
    """A [`terms`](https://docs.opensearch.org/latest/aggregations/bucket/terms/)
    bucket aggregation -- one bucket per distinct value of `field`."""

    field: str
    """Required. The column to bucket by."""

    size: int
    """Optional. Maximum number of buckets to return. Capped server-side."""

    shard_size: int
    """Optional. Number of candidate buckets collected per shard before the
    final reduce. Capped server-side."""

    min_doc_count: int
    """Optional. Minimum document count for a bucket to be returned. Default
    `1`."""

    shard_min_doc_count: int
    """Optional. Per-shard minimum document count before a bucket is
    considered."""

    show_term_doc_count_error: bool
    """Optional. Whether to return the per-bucket document-count error
    bound."""

    order: BucketOrder
    """Optional. Bucket sort order -- a `{metric: "asc|desc"}` object or an
    array of them."""

    include: Union[str, List[ScalarValue]]
    """Optional. Terms to include -- a regex string or an array of exact
    values."""

    exclude: Union[str, List[ScalarValue]]
    """Optional. Terms to exclude -- a regex string or an array of exact
    values."""

    missing: ScalarValue
    """Optional. Bucket value assigned to documents missing `field`."""

    collect_mode: str
    """Optional. `breadth_first` or `depth_first` sub-aggregation collection
    strategy."""

    execution_hint: str
    """Optional. Internal execution strategy hint (`map` /
    `global_ordinals`)."""

    format: str
    """Optional. Format applied to the bucket key in the response."""

    value_type: str
    """Optional. Explicit value type for the field when it cannot be
    inferred."""

Attributes

field instance-attribute

field: str

Required. The column to bucket by.

size instance-attribute

size: int

Optional. Maximum number of buckets to return. Capped server-side.

shard_size instance-attribute

shard_size: int

Optional. Number of candidate buckets collected per shard before the final reduce. Capped server-side.

min_doc_count instance-attribute

min_doc_count: int

Optional. Minimum document count for a bucket to be returned. Default 1.

shard_min_doc_count instance-attribute

shard_min_doc_count: int

Optional. Per-shard minimum document count before a bucket is considered.

show_term_doc_count_error instance-attribute

show_term_doc_count_error: bool

Optional. Whether to return the per-bucket document-count error bound.

order instance-attribute

order: BucketOrder

Optional. Bucket sort order -- a {metric: "asc|desc"} object or an array of them.

include instance-attribute

include: Union[str, List[ScalarValue]]

Optional. Terms to include -- a regex string or an array of exact values.

exclude instance-attribute

exclude: Union[str, List[ScalarValue]]

Optional. Terms to exclude -- a regex string or an array of exact values.

missing instance-attribute

missing: ScalarValue

Optional. Bucket value assigned to documents missing field.

collect_mode instance-attribute

collect_mode: str

Optional. breadth_first or depth_first sub-aggregation collection strategy.

execution_hint instance-attribute

execution_hint: str

Optional. Internal execution strategy hint (map / global_ordinals).

format instance-attribute

format: str

Optional. Format applied to the bucket key in the response.

value_type instance-attribute

value_type: str

Optional. Explicit value type for the field when it cannot be inferred.

synapseclient.models.search_dsl.HistogramAggregation

Bases: KeyedBucketOption, HistogramBoundsOptions

A histogram bucket aggregation over a numeric column. Must specify extended_bounds or hard_bounds so the bucket count is bounded.

Source code in synapseclient/models/search_dsl.py
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
class HistogramAggregation(KeyedBucketOption, HistogramBoundsOptions, total=False):
    """A [`histogram`](https://docs.opensearch.org/latest/aggregations/bucket/histogram/)
    bucket aggregation over a numeric column. Must specify `extended_bounds` or
    `hard_bounds` so the bucket count is bounded."""

    field: str
    """Required. The numeric column to bucket."""

    interval: float
    """Required. Bucket width. Must be positive."""

    min_doc_count: int
    """Optional. Minimum document count for a bucket to be returned."""

    offset: float
    """Optional. Shifts bucket boundaries by this amount."""

    order: BucketOrder
    """Optional. Bucket sort order -- a `{metric: "asc|desc"}` object or an
    array of them."""

    missing: ScalarValue
    """Optional. Bucket value assigned to documents missing `field`."""

    format: str
    """Optional. Format applied to the bucket key in the response."""

Attributes

field instance-attribute

field: str

Required. The numeric column to bucket.

interval instance-attribute

interval: float

Required. Bucket width. Must be positive.

min_doc_count instance-attribute

min_doc_count: int

Optional. Minimum document count for a bucket to be returned.

offset instance-attribute

offset: float

Optional. Shifts bucket boundaries by this amount.

order instance-attribute

order: BucketOrder

Optional. Bucket sort order -- a {metric: "asc|desc"} object or an array of them.

missing instance-attribute

missing: ScalarValue

Optional. Bucket value assigned to documents missing field.

format instance-attribute

format: str

Optional. Format applied to the bucket key in the response.

synapseclient.models.search_dsl.DateHistogramAggregation

Bases: KeyedBucketOption, HistogramBoundsOptions

A date_histogram bucket aggregation over a date column. Must specify extended_bounds or hard_bounds so the bucket count is bounded.

Source code in synapseclient/models/search_dsl.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
class DateHistogramAggregation(KeyedBucketOption, HistogramBoundsOptions, total=False):
    """A [`date_histogram`](https://docs.opensearch.org/latest/aggregations/bucket/date-histogram/)
    bucket aggregation over a date column. Must specify `extended_bounds` or
    `hard_bounds` so the bucket count is bounded."""

    field: str
    """Required. The date column to bucket."""

    calendar_interval: str
    """Optional. Calendar-aware interval (e.g. `month`, `year`). Mutually
    exclusive with `fixed_interval`."""

    fixed_interval: str
    """Optional. Fixed-duration interval (e.g. `30d`, `12h`). Mutually
    exclusive with `calendar_interval`."""

    interval: str
    """Optional. Legacy interval (use `calendar_interval` / `fixed_interval`
    instead)."""

    min_doc_count: int
    """Optional. Minimum document count for a bucket to be returned."""

    offset: str
    """Optional. Shifts bucket boundaries by this duration."""

    time_zone: str
    """Optional. UTC offset or IANA zone used to compute bucket boundaries."""

    order: BucketOrder
    """Optional. Bucket sort order -- a `{metric: "asc|desc"}` object or an
    array of them."""

    missing: ScalarValue
    """Optional. Bucket value assigned to documents missing `field`."""

    format: str
    """Optional. Date format applied to the bucket key in the response."""

Attributes

field instance-attribute

field: str

Required. The date column to bucket.

calendar_interval instance-attribute

calendar_interval: str

Optional. Calendar-aware interval (e.g. month, year). Mutually exclusive with fixed_interval.

fixed_interval instance-attribute

fixed_interval: str

Optional. Fixed-duration interval (e.g. 30d, 12h). Mutually exclusive with calendar_interval.

interval instance-attribute

interval: str

Optional. Legacy interval (use calendar_interval / fixed_interval instead).

min_doc_count instance-attribute

min_doc_count: int

Optional. Minimum document count for a bucket to be returned.

offset instance-attribute

offset: str

Optional. Shifts bucket boundaries by this duration.

time_zone instance-attribute

time_zone: str

Optional. UTC offset or IANA zone used to compute bucket boundaries.

order instance-attribute

order: BucketOrder

Optional. Bucket sort order -- a {metric: "asc|desc"} object or an array of them.

missing instance-attribute

missing: ScalarValue

Optional. Bucket value assigned to documents missing field.

format instance-attribute

format: str

Optional. Date format applied to the bucket key in the response.

synapseclient.models.search_dsl.RangeAggregation

Bases: KeyedBucketOption

A range bucket aggregation -- one bucket per caller-defined numeric range.

Source code in synapseclient/models/search_dsl.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
class RangeAggregation(KeyedBucketOption, total=False):
    """A [`range`](https://docs.opensearch.org/latest/aggregations/bucket/range/)
    bucket aggregation -- one bucket per caller-defined numeric range."""

    field: str
    """Required. The numeric column to bucket."""

    ranges: List[Dict[str, Any]]
    """Required. The [bucket ranges](https://docs.opensearch.org/latest/aggregations/bucket/range/),
    each `{"from": <lower>, "to": <upper>, "key": "<label>"}` covering
    `[from, to)`. At least one of `from` / `to` is required per entry. Untyped
    because `from` is a Python keyword and cannot be a `TypedDict` field."""

    missing: ScalarValue
    """Optional. Value assigned to documents missing `field`."""

    format: str
    """Optional. Format applied to the bucket key in the response."""

Attributes

field instance-attribute

field: str

Required. The numeric column to bucket.

ranges instance-attribute

ranges: List[Dict[str, Any]]

Required. The bucket ranges, each {"from": <lower>, "to": <upper>, "key": "<label>"} covering [from, to). At least one of from / to is required per entry. Untyped because from is a Python keyword and cannot be a TypedDict field.

missing instance-attribute

missing: ScalarValue

Optional. Value assigned to documents missing field.

format instance-attribute

format: str

Optional. Format applied to the bucket key in the response.

synapseclient.models.search_dsl.DateRangeAggregation

Bases: KeyedBucketOption

A date_range bucket aggregation -- one bucket per caller-defined date range.

Source code in synapseclient/models/search_dsl.py
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
class DateRangeAggregation(KeyedBucketOption, total=False):
    """A [`date_range`](https://docs.opensearch.org/latest/aggregations/bucket/date-range/)
    bucket aggregation -- one bucket per caller-defined date range."""

    field: str
    """Required. The date column to bucket."""

    ranges: List[Dict[str, Any]]
    """Required. The [bucket ranges](https://docs.opensearch.org/latest/aggregations/bucket/date-range/),
    each `{"from": <lower>, "to": <upper>, "key": "<label>"}`. Bound values may
    be dates or date-math expressions. Untyped because `from` is a Python
    keyword and cannot be a `TypedDict` field."""

    time_zone: str
    """Optional. UTC offset or IANA zone used to interpret the range bounds."""

    missing: ScalarValue
    """Optional. Value assigned to documents missing `field`."""

    format: str
    """Optional. Date format applied to the bucket key in the response."""

Attributes

field instance-attribute

field: str

Required. The date column to bucket.

ranges instance-attribute

ranges: List[Dict[str, Any]]

Required. The bucket ranges, each {"from": <lower>, "to": <upper>, "key": "<label>"}. Bound values may be dates or date-math expressions. Untyped because from is a Python keyword and cannot be a TypedDict field.

time_zone instance-attribute

time_zone: str

Optional. UTC offset or IANA zone used to interpret the range bounds.

missing instance-attribute

missing: ScalarValue

Optional. Value assigned to documents missing field.

format instance-attribute

format: str

Optional. Date format applied to the bucket key in the response.

synapseclient.models.search_dsl.MissingAggregation

Bases: TypedDict

A missing bucket aggregation -- a single bucket of documents that have no value for field.

Source code in synapseclient/models/search_dsl.py
815
816
817
818
819
820
821
822
823
824
825
class MissingAggregation(TypedDict, total=False):
    """A [`missing`](https://docs.opensearch.org/latest/aggregations/bucket/missing/)
    bucket aggregation -- a single bucket of documents that have no value for
    `field`."""

    field: str
    """Required. The column whose missing values are bucketed."""

    missing: ScalarValue
    """Optional. Placeholder value treated as present (so those documents are
    excluded from the missing bucket)."""

Attributes

field instance-attribute

field: str

Required. The column whose missing values are bucketed.

missing instance-attribute

missing: ScalarValue

Optional. Placeholder value treated as present (so those documents are excluded from the missing bucket).

synapseclient.models.search_dsl.MinAggregation

Bases: MetricAggregation, MissingValueOption

A min metric aggregation -- the minimum value of a numeric column.

Source code in synapseclient/models/search_dsl.py
828
829
830
831
832
833
834
class MinAggregation(MetricAggregation, MissingValueOption, total=False):
    """A [`min`](https://docs.opensearch.org/latest/aggregations/metric/minimum/)
    metric aggregation -- the minimum value of a numeric column."""

    value_type: str
    """Optional. Explicit value type for the field when it cannot be
    inferred."""

Attributes

value_type instance-attribute

value_type: str

Optional. Explicit value type for the field when it cannot be inferred.

synapseclient.models.search_dsl.MaxAggregation

Bases: MetricAggregation, MissingValueOption

A max metric aggregation -- the maximum value of a numeric column.

Source code in synapseclient/models/search_dsl.py
837
838
839
840
841
842
843
class MaxAggregation(MetricAggregation, MissingValueOption, total=False):
    """A [`max`](https://docs.opensearch.org/latest/aggregations/metric/maximum/)
    metric aggregation -- the maximum value of a numeric column."""

    value_type: str
    """Optional. Explicit value type for the field when it cannot be
    inferred."""

Attributes

value_type instance-attribute

value_type: str

Optional. Explicit value type for the field when it cannot be inferred.

synapseclient.models.search_dsl.AvgAggregation

Bases: MetricAggregation, MissingValueOption

An avg metric aggregation -- the mean value of a numeric column.

Source code in synapseclient/models/search_dsl.py
846
847
848
849
850
851
852
class AvgAggregation(MetricAggregation, MissingValueOption, total=False):
    """An [`avg`](https://docs.opensearch.org/latest/aggregations/metric/average/)
    metric aggregation -- the mean value of a numeric column."""

    value_type: str
    """Optional. Explicit value type for the field when it cannot be
    inferred."""

Attributes

value_type instance-attribute

value_type: str

Optional. Explicit value type for the field when it cannot be inferred.

synapseclient.models.search_dsl.SumAggregation

Bases: MetricAggregation, MissingValueOption

A sum metric aggregation -- the sum of a numeric column.

Source code in synapseclient/models/search_dsl.py
855
856
857
class SumAggregation(MetricAggregation, MissingValueOption, total=False):
    """A [`sum`](https://docs.opensearch.org/latest/aggregations/metric/sum/)
    metric aggregation -- the sum of a numeric column."""

synapseclient.models.search_dsl.StatsAggregation

Bases: MissingValueOption

A stats metric aggregation -- count, min, max, avg, and sum of a numeric column in one pass.

Source code in synapseclient/models/search_dsl.py
860
861
862
863
864
865
866
867
868
869
class StatsAggregation(MissingValueOption, total=False):
    """A [`stats`](https://docs.opensearch.org/latest/aggregations/metric/stats/)
    metric aggregation -- count, min, max, avg, and sum of a numeric column in
    one pass."""

    field: str
    """Required. The numeric column to aggregate."""

    format: str
    """Optional. Format applied to the result values."""

Attributes

field instance-attribute

field: str

Required. The numeric column to aggregate.

format instance-attribute

format: str

Optional. Format applied to the result values.

synapseclient.models.search_dsl.ExtendedStatsAggregation

Bases: MissingValueOption

An extended_stats metric aggregation -- stats plus variance, standard deviation, and standard-deviation bounds.

Source code in synapseclient/models/search_dsl.py
872
873
874
875
876
877
878
879
880
881
882
883
884
885
class ExtendedStatsAggregation(MissingValueOption, total=False):
    """An [`extended_stats`](https://docs.opensearch.org/latest/aggregations/metric/extended-stats/)
    metric aggregation -- `stats` plus variance, standard deviation, and
    standard-deviation bounds."""

    field: str
    """Required. The numeric column to aggregate."""

    sigma: float
    """Optional. Number of standard deviations for the std-deviation bounds.
    Default `2.0`."""

    format: str
    """Optional. Format applied to the result values."""

Attributes

field instance-attribute

field: str

Required. The numeric column to aggregate.

sigma instance-attribute

sigma: float

Optional. Number of standard deviations for the std-deviation bounds. Default 2.0.

format instance-attribute

format: str

Optional. Format applied to the result values.

synapseclient.models.search_dsl.ValueCountAggregation

Bases: MissingValueOption

A value_count metric aggregation -- the number of values extracted for a column.

Source code in synapseclient/models/search_dsl.py
888
889
890
891
892
893
894
895
896
class ValueCountAggregation(MissingValueOption, total=False):
    """A [`value_count`](https://docs.opensearch.org/latest/aggregations/metric/value-count/)
    metric aggregation -- the number of values extracted for a column."""

    field: str
    """Required. The column to count values of."""

    format: str
    """Optional. Format applied to the result value."""

Attributes

field instance-attribute

field: str

Required. The column to count values of.

format instance-attribute

format: str

Optional. Format applied to the result value.

synapseclient.models.search_dsl.CardinalityAggregation

Bases: MissingValueOption

A cardinality metric aggregation -- an approximate distinct-value count of a column.

Source code in synapseclient/models/search_dsl.py
899
900
901
902
903
904
905
906
907
908
909
910
911
class CardinalityAggregation(MissingValueOption, total=False):
    """A [`cardinality`](https://docs.opensearch.org/latest/aggregations/metric/cardinality/)
    metric aggregation -- an approximate distinct-value count of a column."""

    field: str
    """Required. The column whose distinct values are counted."""

    precision_threshold: int
    """Optional. Count below which the result is near-exact, trading memory for
    accuracy. Capped server-side."""

    execution_hint: str
    """Optional. Internal execution strategy hint."""

Attributes

field instance-attribute

field: str

Required. The column whose distinct values are counted.

precision_threshold instance-attribute

precision_threshold: int

Optional. Count below which the result is near-exact, trading memory for accuracy. Capped server-side.

execution_hint instance-attribute

execution_hint: str

Optional. Internal execution strategy hint.

synapseclient.models.search_dsl.FiltersAggregation

Bases: TypedDict

A filters multi-bucket aggregation. Each entry of filters is a named bucket whose documents match its Query. The named (keyed) form is the supported contract; each query is validated identically to the top-level query and is scoped by it.

Source code in synapseclient/models/search_dsl.py
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
class FiltersAggregation(TypedDict, total=False):
    """A [`filters`](https://docs.opensearch.org/latest/aggregations/bucket/filters/)
    multi-bucket aggregation. Each entry of `filters` is a named bucket whose
    documents match its [Query][synapseclient.models.search_dsl.Query]. The
    named (keyed) form is the supported contract; each query is validated
    identically to the top-level `query` and is scoped by it."""

    filters: Dict[str, Query]
    """Required. Named buckets, keyed by caller-chosen name; each value is a
    [Query][synapseclient.models.search_dsl.Query] selecting that bucket's
    documents."""

    other_bucket: bool
    """Optional. When `true`, adds a bucket for documents that match none of
    the named filters."""

    other_bucket_key: str
    """Optional. The key under which the other bucket is returned."""

    keyed: bool
    """Optional. Whether buckets are returned as a keyed object (default)
    rather than an array."""

Attributes

filters instance-attribute

filters: Dict[str, Query]

Required. Named buckets, keyed by caller-chosen name; each value is a Query selecting that bucket's documents.

other_bucket instance-attribute

other_bucket: bool

Optional. When true, adds a bucket for documents that match none of the named filters.

other_bucket_key instance-attribute

other_bucket_key: str

Optional. The key under which the other bucket is returned.

keyed instance-attribute

keyed: bool

Optional. Whether buckets are returned as a keyed object (default) rather than an array.

synapseclient.models.search_dsl.ExtendedBounds

Bases: TypedDict

Min/max bounds that force a histogram or date_histogram to emit buckets across the full range (used as extended_bounds or hard_bounds). Bounding the range is what caps the bucket count.

Source code in synapseclient/models/search_dsl.py
588
589
590
591
592
593
594
595
596
597
598
599
600
class ExtendedBounds(TypedDict, total=False):
    """Min/max bounds that force a [`histogram`](https://docs.opensearch.org/latest/aggregations/bucket/histogram/)
    or [`date_histogram`](https://docs.opensearch.org/latest/aggregations/bucket/date-histogram/)
    to emit buckets across the full range (used as `extended_bounds` or
    `hard_bounds`). Bounding the range is what caps the bucket count."""

    min: ScalarValue
    """Lower bound. A number, or a date / date-math string on a
    `date_histogram`."""

    max: ScalarValue
    """Upper bound. A number, or a date / date-math string on a
    `date_histogram`."""

Attributes

min instance-attribute

min: ScalarValue

Lower bound. A number, or a date / date-math string on a date_histogram.

max instance-attribute

max: ScalarValue

Upper bound. A number, or a date / date-math string on a date_histogram.

synapseclient.models.search_dsl.HistogramBoundsOptions

Bases: TypedDict

The extended/hard bounds options shared by the histogram and date_histogram aggregations.

Source code in synapseclient/models/search_dsl.py
603
604
605
606
607
608
609
610
611
612
class HistogramBoundsOptions(TypedDict, total=False):
    """The extended/hard bounds options shared by the `histogram` and
    `date_histogram` aggregations."""

    extended_bounds: ExtendedBounds
    """Optional. Forces buckets to span at least this min/max range."""

    hard_bounds: ExtendedBounds
    """Optional. Restricts buckets to this min/max range (values outside are
    dropped)."""

Attributes

extended_bounds instance-attribute

extended_bounds: ExtendedBounds

Optional. Forces buckets to span at least this min/max range.

hard_bounds instance-attribute

hard_bounds: ExtendedBounds

Optional. Restricts buckets to this min/max range (values outside are dropped).

synapseclient.models.search_dsl.KeyedBucketOption

Bases: TypedDict

The keyed-output option shared by the bucketing aggregations.

Source code in synapseclient/models/search_dsl.py
615
616
617
618
619
620
class KeyedBucketOption(TypedDict, total=False):
    """The keyed-output option shared by the bucketing aggregations."""

    keyed: bool
    """Optional. Whether to return buckets as a keyed object rather than an
    array."""

Attributes

keyed instance-attribute

keyed: bool

Optional. Whether to return buckets as a keyed object rather than an array.

synapseclient.models.search_dsl.MetricAggregation

Bases: TypedDict

Common options for the single-value numeric metric aggregations (avg, max, min, sum).

Source code in synapseclient/models/search_dsl.py
623
624
625
626
627
628
629
630
631
class MetricAggregation(TypedDict, total=False):
    """Common options for the single-value numeric metric aggregations (`avg`,
    `max`, `min`, `sum`)."""

    field: str
    """Required. The numeric column to aggregate."""

    format: str
    """Optional. Format applied to the result value."""

Attributes

field instance-attribute

field: str

Required. The numeric column to aggregate.

format instance-attribute

format: str

Optional. Format applied to the result value.

synapseclient.models.search_dsl.MissingValueOption

Bases: TypedDict

The missing-value substitution option shared by the metric aggregations.

Source code in synapseclient/models/search_dsl.py
634
635
636
637
638
639
class MissingValueOption(TypedDict, total=False):
    """The missing-value substitution option shared by the metric
    aggregations."""

    missing: ScalarValue
    """Optional. Value substituted for documents missing `field`."""

Attributes

missing instance-attribute

missing: ScalarValue

Optional. Value substituted for documents missing field.

Highlighting, source filtering, collapse, and rescore

synapseclient.models.search_dsl.Highlight

Bases: HighlightCommonOptions

A highlight block. Adds matched-term snippet fragments to each hit. Top-level options apply to every highlighted field unless overridden in a per-field block under fields.

Source code in synapseclient/models/search_dsl.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
class Highlight(HighlightCommonOptions, total=False):
    """A [highlight](https://docs.opensearch.org/latest/search-plugins/searching-data/highlight/)
    block. Adds matched-term snippet fragments to each hit. Top-level options
    apply to every highlighted field unless overridden in a per-field block
    under `fields`."""

    fields: Dict[str, HighlightField]
    """Required. The columns to highlight, keyed by column name; each value is
    its per-field option overrides."""

    type: str
    """Optional. Default highlighter implementation: `unified` (default),
    `plain`, or `fvh`. The `semantic` highlighter is rejected."""

    number_of_fragments: int
    """Optional. Maximum number of fragments per field. Capped server-side."""

    encoder: str
    """Optional. How highlighted text is encoded: `default` or `html`."""

    pre_tags: List[str]
    """Optional. Opening tags wrapped around highlighted terms. Default
    `<em>`."""

    post_tags: List[str]
    """Optional. Closing tags wrapped around highlighted terms. Default
    `</em>`."""

    highlight_query: Query
    """Optional. A separate query used to select the terms to highlight across
    all fields."""

Attributes

fields instance-attribute

Required. The columns to highlight, keyed by column name; each value is its per-field option overrides.

type instance-attribute

type: str

Optional. Default highlighter implementation: unified (default), plain, or fvh. The semantic highlighter is rejected.

number_of_fragments instance-attribute

number_of_fragments: int

Optional. Maximum number of fragments per field. Capped server-side.

encoder instance-attribute

encoder: str

Optional. How highlighted text is encoded: default or html.

pre_tags instance-attribute

pre_tags: List[str]

Optional. Opening tags wrapped around highlighted terms. Default <em>.

post_tags instance-attribute

post_tags: List[str]

Optional. Closing tags wrapped around highlighted terms. Default </em>.

highlight_query instance-attribute

highlight_query: Query

Optional. A separate query used to select the terms to highlight across all fields.

synapseclient.models.search_dsl.HighlightField

Bases: HighlightCommonOptions

Per-field highlight options, carried as the value of a Highlight fields entry (the map key is the column name). Any option set here overrides the top-level highlight option for this field.

Source code in synapseclient/models/search_dsl.py
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
class HighlightField(HighlightCommonOptions, total=False):
    """Per-field [highlight](https://docs.opensearch.org/latest/search-plugins/searching-data/highlight/)
    options, carried as the value of a
    [Highlight][synapseclient.models.search_dsl.Highlight] `fields` entry (the
    map key is the column name). Any option set here overrides the top-level
    highlight option for this field."""

    type: str
    """Optional. Highlighter implementation: `unified` (default), `plain`, or
    `fvh`. The `semantic` highlighter is rejected."""

    number_of_fragments: int
    """Optional. Maximum number of fragments to return for this field. Capped
    server-side."""

    pre_tags: List[str]
    """Optional. Opening tags wrapped around highlighted terms."""

    post_tags: List[str]
    """Optional. Closing tags wrapped around highlighted terms."""

    matched_fields: List[str]
    """Optional. Other fields whose matches also highlight this field (`fvh`
    only)."""

    highlight_query: Query
    """Optional. A separate query used to select the terms to highlight for
    this field."""

Attributes

type instance-attribute

type: str

Optional. Highlighter implementation: unified (default), plain, or fvh. The semantic highlighter is rejected.

number_of_fragments instance-attribute

number_of_fragments: int

Optional. Maximum number of fragments to return for this field. Capped server-side.

pre_tags instance-attribute

pre_tags: List[str]

Optional. Opening tags wrapped around highlighted terms.

post_tags instance-attribute

post_tags: List[str]

Optional. Closing tags wrapped around highlighted terms.

matched_fields instance-attribute

matched_fields: List[str]

Optional. Other fields whose matches also highlight this field (fvh only).

highlight_query instance-attribute

highlight_query: Query

Optional. A separate query used to select the terms to highlight for this field.

synapseclient.models.search_dsl.HighlightCommonOptions

Bases: TypedDict

Highlight options shared by the top-level highlight block and the per-field highlight overrides.

Source code in synapseclient/models/search_dsl.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
class HighlightCommonOptions(TypedDict, total=False):
    """[Highlight](https://docs.opensearch.org/latest/search-plugins/searching-data/highlight/)
    options shared by the top-level highlight block and the per-field highlight
    overrides."""

    fragment_size: int
    """Optional. Maximum characters per highlighted fragment. Capped
    server-side."""

    fragment_offset: int
    """Optional. Character offset at which to start highlighting (`fvh`
    only)."""

    no_match_size: int
    """Optional. Number of leading characters to return when there is no
    match."""

    order: str
    """Optional. Fragment ordering: `none` (default) or `score`."""

    fragmenter: str
    """Optional. Fragmentation strategy: `simple` or `span` (plain
    highlighter)."""

    boundary_scanner: str
    """Optional. Boundary detection: `chars`, `sentence`, or `word`."""

    boundary_scanner_locale: str
    """Optional. Locale used by the boundary scanner."""

    boundary_chars: str
    """Optional. Characters treated as boundaries by the `chars` scanner."""

    boundary_max_scan: int
    """Optional. How far the boundary scanner looks for a boundary."""

    max_fragment_length: int
    """Optional. Maximum length of a fragment."""

    max_analyzer_offset: int
    """Optional. Maximum character offset analyzed for highlighting."""

    phrase_limit: int
    """Optional. Maximum number of matching phrases considered (`fvh`
    only)."""

    require_field_match: bool
    """Optional. Whether only fields that matched the query are highlighted.
    Default `true`."""

    highlight_filter: bool
    """Optional. Whether to highlight only fields that passed the query
    filter."""

    force_source: bool
    """Optional. Whether to highlight from the original `_source` rather than
    stored fields."""

    tags_schema: str
    """Optional. Built-in tag schema (`styled`) for the highlight markup."""

Attributes

fragment_size instance-attribute

fragment_size: int

Optional. Maximum characters per highlighted fragment. Capped server-side.

fragment_offset instance-attribute

fragment_offset: int

Optional. Character offset at which to start highlighting (fvh only).

no_match_size instance-attribute

no_match_size: int

Optional. Number of leading characters to return when there is no match.

order instance-attribute

order: str

Optional. Fragment ordering: none (default) or score.

fragmenter instance-attribute

fragmenter: str

Optional. Fragmentation strategy: simple or span (plain highlighter).

boundary_scanner instance-attribute

boundary_scanner: str

Optional. Boundary detection: chars, sentence, or word.

boundary_scanner_locale instance-attribute

boundary_scanner_locale: str

Optional. Locale used by the boundary scanner.

boundary_chars instance-attribute

boundary_chars: str

Optional. Characters treated as boundaries by the chars scanner.

boundary_max_scan instance-attribute

boundary_max_scan: int

Optional. How far the boundary scanner looks for a boundary.

max_fragment_length instance-attribute

max_fragment_length: int

Optional. Maximum length of a fragment.

max_analyzer_offset instance-attribute

max_analyzer_offset: int

Optional. Maximum character offset analyzed for highlighting.

phrase_limit instance-attribute

phrase_limit: int

Optional. Maximum number of matching phrases considered (fvh only).

require_field_match instance-attribute

require_field_match: bool

Optional. Whether only fields that matched the query are highlighted. Default true.

highlight_filter instance-attribute

highlight_filter: bool

Optional. Whether to highlight only fields that passed the query filter.

force_source instance-attribute

force_source: bool

Optional. Whether to highlight from the original _source rather than stored fields.

tags_schema instance-attribute

tags_schema: str

Optional. Built-in tag schema (styled) for the highlight markup.

synapseclient.models.search_dsl.SourceFilter

Bases: TypedDict

A source filter selecting which columns are returned on each hit. Carried as the SearchQuery source field. Only this typed {includes, excludes} form is accepted -- the boolean (true / false) and bare-array shorthands are not.

Source code in synapseclient/models/search_dsl.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
class SourceFilter(TypedDict, total=False):
    """A [source filter](https://docs.opensearch.org/latest/search-plugins/searching-data/retrieve-specific-fields/)
    selecting which columns are returned on each hit. Carried as the
    [SearchQuery][synapseclient.models.SearchQuery] `source` field. Only this
    typed `{includes, excludes}` form is accepted -- the boolean (`true` /
    `false`) and bare-array shorthands are not."""

    includes: List[str]
    """Optional. Columns to include. When empty or absent, all columns are
    included (subject to `excludes`)."""

    excludes: List[str]
    """Optional. Columns to exclude. Applied after `includes`."""

Attributes

includes instance-attribute

includes: List[str]

Optional. Columns to include. When empty or absent, all columns are included (subject to excludes).

excludes instance-attribute

excludes: List[str]

Optional. Columns to exclude. Applied after includes.

synapseclient.models.search_dsl.FieldCollapse

Bases: TypedDict

A collapse block. Returns only the top hit per distinct value of field, deduplicating the result list.

Source code in synapseclient/models/search_dsl.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
class FieldCollapse(TypedDict, total=False):
    """A [collapse](https://docs.opensearch.org/latest/search-plugins/searching-data/collapse-search/)
    block. Returns only the top hit per distinct value of `field`,
    deduplicating the result list."""

    field: str
    """Required. The column to collapse on. Must be a keyword / doc-values
    column."""

    max_concurrent_group_searches: int
    """Optional. Maximum concurrent searches run to expand groups. Capped
    server-side."""

Attributes

field instance-attribute

field: str

Required. The column to collapse on. Must be a keyword / doc-values column.

max_concurrent_group_searches instance-attribute

max_concurrent_group_searches: int

Optional. Maximum concurrent searches run to expand groups. Capped server-side.

synapseclient.models.search_dsl.Rescore

Bases: TypedDict

A rescore stage. Re-ranks the top window_size hits from the main query using a secondary scoring query. A single stage is supported.

Source code in synapseclient/models/search_dsl.py
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
class Rescore(TypedDict, total=False):
    """A [rescore](https://docs.opensearch.org/latest/query-dsl/rescore/) stage.
    Re-ranks the top `window_size` hits from the main query using a secondary
    scoring query. A single stage is supported."""

    window_size: int
    """Optional. Number of top hits per shard that are re-scored. Capped
    server-side."""

    query: RescoreQuery
    """Required. The secondary scoring query and how its score blends with the
    original."""

Attributes

window_size instance-attribute

window_size: int

Optional. Number of top hits per shard that are re-scored. Capped server-side.

query instance-attribute

query: RescoreQuery

Required. The secondary scoring query and how its score blends with the original.

synapseclient.models.search_dsl.RescoreQuery

Bases: TypedDict

The secondary-scoring portion of a rescore stage: a query whose score is blended with the original score.

Source code in synapseclient/models/search_dsl.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
class RescoreQuery(TypedDict, total=False):
    """The secondary-scoring portion of a
    [rescore](https://docs.opensearch.org/latest/query-dsl/rescore/) stage: a
    query whose score is blended with the original score."""

    rescore_query: Query
    """Required. The query used to re-score the top window of hits."""

    query_weight: float
    """Optional. Weight applied to the original query score. Default `1.0`."""

    rescore_query_weight: float
    """Optional. Weight applied to the rescore-query score. Default `1.0`."""

    score_mode: str
    """Optional. How the two scores combine: `total` (default), `multiply`,
    `avg`, `max`, or `min`."""

Attributes

rescore_query instance-attribute

rescore_query: Query

Required. The query used to re-score the top window of hits.

query_weight instance-attribute

query_weight: float

Optional. Weight applied to the original query score. Default 1.0.

rescore_query_weight instance-attribute

rescore_query_weight: float

Optional. Weight applied to the rescore-query score. Default 1.0.

score_mode instance-attribute

score_mode: str

Optional. How the two scores combine: total (default), multiply, avg, max, or min.