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

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

Store metadata about a SearchIndex including the annotations. 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.

 

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;
    defining_sql="SELECT * FROM syn67890",
)
index = index.store()
print(f"Created SearchIndex: {index.id}")
Source code in synapseclient/models/protocols/search_index_protocol.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def store(
    self,
    dry_run: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Store metadata about a SearchIndex including the annotations. 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
        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;
            defining_sql="SELECT * FROM syn67890",
        )
        index = index.store()
        print(f"Created SearchIndex: {index.id}")
        ```
    """
    return self

get

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

Get the metadata about the SearchIndex from Synapse. 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.

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex

syn = Synapse()
syn.login()

index = SearchIndex(id="syn12345").get()
print(index.name, index.defining_sql)
Source code in synapseclient/models/protocols/search_index_protocol.py
 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
def get(
    self,
    include_activity: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Get the metadata about the SearchIndex from Synapse. 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        syn = Synapse()
        syn.login()

        index = SearchIndex(id="syn12345").get()
        print(index.name, index.defining_sql)
        ```
    """
    return self

delete

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

Delete the 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.

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex

syn = Synapse()
syn.login()

SearchIndex(id="syn12345").delete()
Source code in synapseclient/models/protocols/search_index_protocol.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def delete(self, *, synapse_client: Optional[Synapse] = None) -> None:
    """Delete the 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        syn = Synapse()
        syn.login()

        SearchIndex(id="syn12345").delete()
        ```
    """
    return None

query

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

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".

 

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

syn = Synapse()
syn.login()

results = SearchIndex(id="syn12345").query(
    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)
Source code in synapseclient/models/protocols/search_index_protocol.py
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
def query(
    self,
    search_query: "SearchQuery",
    response_parts: Optional[List["SearchQueryPart"]] = None,
    *,
    job_timeout: int = 600,
    synapse_client: Optional[Synapse] = None,
) -> "SearchIndexQuery":
    """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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
        from synapseclient.models.search_dsl import Query

        syn = Synapse()
        syn.login()

        results = SearchIndex(id="syn12345").query(
            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)
        ```
    """
    from synapseclient.models.search_management import SearchIndexQuery

    return SearchIndexQuery()

autocomplete

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

Run a synchronous autocomplete search against this index. The autocomplete endpoint allowlists 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".

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex
from synapseclient.models.search_dsl import Query

syn = Synapse()
syn.login()

index = SearchIndex(id="syn12345")
hits = index.autocomplete(
    query=Query(match_phrase_prefix={"title": {"query": "alz"}}),
)
for hit in hits:
    print(hit.row_id, hit.fields)
Source code in synapseclient/models/protocols/search_index_protocol.py
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
def autocomplete(
    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 allowlists 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex
        from synapseclient.models.search_dsl import Query

        syn = Synapse()
        syn.login()

        index = SearchIndex(id="syn12345")
        hits = index.autocomplete(
            query=Query(match_phrase_prefix={"title": {"query": "alz"}}),
        )
        for hit in hits:
            print(hit.row_id, hit.fields)
        ```
    """
    return []

get_permissions

get_permissions(*, 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

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

permissions = File(id="syn123").get_permissions()

Getting access types list from the Permissions object

permissions.access_types
Source code in synapseclient/models/protocols/access_control_protocol.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def get_permissions(
    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
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        permissions = File(id="syn123").get_permissions()
        ```

        Getting access types list from the Permissions object

        ```
        permissions.access_types
        ```
    """
    return self

get_acl

get_acl(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/protocols/access_control_protocol.py
 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
def get_acl(
    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 [""]

set_permissions

set_permissions(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]]

An Access Control List object

Setting permissions

Grant all registered users download access

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])

Grant the public view access

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def set_permissions(
    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

    Example: Setting permissions
        Grant all registered users download access

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

        syn = Synapse()
        syn.login()

        File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
        ```

        Grant the public view access

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

        syn = Synapse()
        syn.login()

        File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
        ```
    """
    return {}

delete_permissions

delete_permissions(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, *, benefactor_tracker: Optional[BenefactorTracker] = None, synapse_client: Optional[Synapse] = 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 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" and "file" (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

benefactor_tracker

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

TYPE: Optional[BenefactorTracker] 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
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
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").delete_permissions()
Delete permissions recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

# Delete permissions for this folder only (does not affect children)
Folder(id="syn123").delete_permissions()

# Delete permissions for all files and folders directly within this folder,
# but not the folder itself
Folder(id="syn123").delete_permissions(
    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
Folder(id="syn123").delete_permissions(
    recursive=True,
    include_container_content=True
)

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

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

# Dry run example: Log what would be deleted without making changes
Folder(id="syn123").delete_permissions(
    recursive=True,
    include_container_content=True,
    dry_run=True
)
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def delete_permissions(
    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,
    *,
    benefactor_tracker: Optional["BenefactorTracker"] = None,
    synapse_client: Optional[Synapse] = 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` 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" and "file" (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.
        benefactor_tracker: Optional tracker for managing benefactor relationships.
            Used for recursive functionality to track which entities will be affected
        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:
        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
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        File(id="syn123").delete_permissions()

        ```

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

        syn = Synapse()
        syn.login()

        # Delete permissions for this folder only (does not affect children)
        Folder(id="syn123").delete_permissions()

        # Delete permissions for all files and folders directly within this folder,
        # but not the folder itself
        Folder(id="syn123").delete_permissions(
            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
        Folder(id="syn123").delete_permissions(
            recursive=True,
            include_container_content=True
        )

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

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

        # Dry run example: Log what would be deleted without making changes
        Folder(id="syn123").delete_permissions(
            recursive=True,
            include_container_content=True,
            dry_run=True
        )
        ```
    """
    return None

list_acl

list_acl(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" and "file" (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
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

acl_result = File(id="syn123").list_acl()
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)
List ACLs recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

acl_result = Folder(id="syn123").list_acl(
    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 = Folder(id="syn123").list_acl(
    recursive=True,
    include_container_content=True,
    target_entity_types=["folder"]
)
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.

from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

acl_result = Folder(id="syn123").list_acl(
    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)
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def list_acl(
    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" and "file" (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
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        acl_result = File(id="syn123").list_acl()
        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)

        ```

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

        syn = Synapse()
        syn.login()

        acl_result = Folder(id="syn123").list_acl(
            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 = Folder(id="syn123").list_acl(
            recursive=True,
            include_container_content=True,
            target_entity_types=["folder"]
        )
        ```

    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
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        acl_result = Folder(id="syn123").list_acl(
            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)
        ```
    """
    return AclListResult()

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>).

synapseclient.models.protocols.search_index_protocol.SearchIndexSynchronousProtocol

Bases: Protocol

Protocol defining the synchronous interface for SearchIndex operations.

Source code in synapseclient/models/protocols/search_index_protocol.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 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
class SearchIndexSynchronousProtocol(Protocol):
    """Protocol defining the synchronous interface for SearchIndex operations."""

    def store(
        self,
        dry_run: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Self":
        """Store metadata about a SearchIndex including the annotations. 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
            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;
                defining_sql="SELECT * FROM syn67890",
            )
            index = index.store()
            print(f"Created SearchIndex: {index.id}")
            ```
        """
        return self

    def get(
        self,
        include_activity: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Self":
        """Get the metadata about the SearchIndex from Synapse. 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
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex

            syn = Synapse()
            syn.login()

            index = SearchIndex(id="syn12345").get()
            print(index.name, index.defining_sql)
            ```
        """
        return self

    def delete(self, *, synapse_client: Optional[Synapse] = None) -> None:
        """Delete the 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
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex

            syn = Synapse()
            syn.login()

            SearchIndex(id="syn12345").delete()
            ```
        """
        return None

    def query(
        self,
        search_query: "SearchQuery",
        response_parts: Optional[List["SearchQueryPart"]] = None,
        *,
        job_timeout: int = 600,
        synapse_client: Optional[Synapse] = None,
    ) -> "SearchIndexQuery":
        """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
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
            from synapseclient.models.search_dsl import Query

            syn = Synapse()
            syn.login()

            results = SearchIndex(id="syn12345").query(
                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)
            ```
        """
        from synapseclient.models.search_management import SearchIndexQuery

        return SearchIndexQuery()

    def autocomplete(
        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 allowlists 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
            from synapseclient import Synapse
            from synapseclient.models import SearchIndex
            from synapseclient.models.search_dsl import Query

            syn = Synapse()
            syn.login()

            index = SearchIndex(id="syn12345")
            hits = index.autocomplete(
                query=Query(match_phrase_prefix={"title": {"query": "alz"}}),
            )
            for hit in hits:
                print(hit.row_id, hit.fields)
            ```
        """
        return []

Methods:

store

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

Store metadata about a SearchIndex including the annotations. 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.

 

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;
    defining_sql="SELECT * FROM syn67890",
)
index = index.store()
print(f"Created SearchIndex: {index.id}")
Source code in synapseclient/models/protocols/search_index_protocol.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def store(
    self,
    dry_run: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Store metadata about a SearchIndex including the annotations. 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
        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;
            defining_sql="SELECT * FROM syn67890",
        )
        index = index.store()
        print(f"Created SearchIndex: {index.id}")
        ```
    """
    return self

get

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

Get the metadata about the SearchIndex from Synapse. 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.

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex

syn = Synapse()
syn.login()

index = SearchIndex(id="syn12345").get()
print(index.name, index.defining_sql)
Source code in synapseclient/models/protocols/search_index_protocol.py
 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
def get(
    self,
    include_activity: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Self":
    """Get the metadata about the SearchIndex from Synapse. 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        syn = Synapse()
        syn.login()

        index = SearchIndex(id="syn12345").get()
        print(index.name, index.defining_sql)
        ```
    """
    return self

delete

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

Delete the 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.

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex

syn = Synapse()
syn.login()

SearchIndex(id="syn12345").delete()
Source code in synapseclient/models/protocols/search_index_protocol.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def delete(self, *, synapse_client: Optional[Synapse] = None) -> None:
    """Delete the 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex

        syn = Synapse()
        syn.login()

        SearchIndex(id="syn12345").delete()
        ```
    """
    return None

query

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

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".

 

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

syn = Synapse()
syn.login()

results = SearchIndex(id="syn12345").query(
    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)
Source code in synapseclient/models/protocols/search_index_protocol.py
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
def query(
    self,
    search_query: "SearchQuery",
    response_parts: Optional[List["SearchQueryPart"]] = None,
    *,
    job_timeout: int = 600,
    synapse_client: Optional[Synapse] = None,
) -> "SearchIndexQuery":
    """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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex, SearchQuery, SearchQueryPart
        from synapseclient.models.search_dsl import Query

        syn = Synapse()
        syn.login()

        results = SearchIndex(id="syn12345").query(
            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)
        ```
    """
    from synapseclient.models.search_management import SearchIndexQuery

    return SearchIndexQuery()

autocomplete

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

Run a synchronous autocomplete search against this index. The autocomplete endpoint allowlists 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".

 

from synapseclient import Synapse
from synapseclient.models import SearchIndex
from synapseclient.models.search_dsl import Query

syn = Synapse()
syn.login()

index = SearchIndex(id="syn12345")
hits = index.autocomplete(
    query=Query(match_phrase_prefix={"title": {"query": "alz"}}),
)
for hit in hits:
    print(hit.row_id, hit.fields)
Source code in synapseclient/models/protocols/search_index_protocol.py
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
def autocomplete(
    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 allowlists 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
        from synapseclient import Synapse
        from synapseclient.models import SearchIndex
        from synapseclient.models.search_dsl import Query

        syn = Synapse()
        syn.login()

        index = SearchIndex(id="syn12345")
        hits = index.autocomplete(
            query=Query(match_phrase_prefix={"title": {"query": "alz"}}),
        )
        for hit in hits:
            print(hit.row_id, hit.fields)
        ```
    """
    return []

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.