Documentation

TsService
in package

Table of Contents

Constants

PROFILE_BULK  : mixed = 'bulk'
PROFILE_WEB  : mixed = 'web'
WEB_CONNECT_TIMEOUT  : mixed = 1.0
WEB_TIMEOUT  : mixed = 3.0
WRITE_THROTTLE_US  : mixed = 500000

Properties

$bulkMode  : bool
$collectionMetaCache  : array<string|int, mixed>
Retrieves the index status of fields in a given collection.
$filterOptionsCache  : array<string, array<string, array<string|int, string>>>
$forceWebTimeouts  : bool
$tsClients  : array<string, Client>

Methods

assignAliasToCollection()  : bool
Updates or creates an alias for a specific collection.
deleteAliasByName()  : array<string|int, mixed>
Deletes a specific alias by its name from TypeSense.
deleteAllCollectionsAndAliases()  : array<string|int, mixed>
Deletes all aliases and collections from TypeSense.
dirtyFlush()  : mixed
enterBulkMode()  : void
Marks the rest of this request as a bulk run, so TypeSense gets the long-timeout client. For work that legitimately streams for minutes but does not run under WP-CLI or cron: an admin flush, or the sitemap walking the whole catalogue.
getAliases()  : mixed
getAllProductListingProducts()  : array<string|int, mixed>
Retrieves all products from the product listing.
getAllSupportProductListingProducts()  : array<string|int, mixed>
Retrieves all support products from the support listing.
getClient()  : Client
getCollectionDocument()  : mixed
getCollectionDocuments()  : mixed
getCollectionFieldsIndexStatus()  : array<string|int, mixed>
getCollectionFilterOptions()  : array<string, array<string|int, string>>
Distinct values for each facetable field of a collection, keyed by the DASHBOARD COLUMN they belong to — so a locale-mapped field like `status` (stored as status.en, status.de, …) reports under `status`, which is the key the filter UI uses.
getCollectionObjectFields()  : array<string|int, mixed>
Returns an array of field names that are object type in the given collection.
getCollections()  : mixed
getCollectionSearchableFields()  : string
Returns a comma-separated list of searchable (indexed string-type) field names for a given collection, suitable for TypeSense's `query_by` parameter.
getCollectionsWithoutAlias()  : array<string|int, mixed>
Returns an array of collections that are not pointed to by any alias.
getProduct()  : Product|false
Creates and retrieves a Product instance based on the provided slug.
getProductById()  : Product|false
Creates and retrieves a Product instance based on the provided ID.
getProductListing()  : array<string|int, mixed>
Retrieves a product listing based on the specified search query.
getProductListingMulti()  : array<string|int, mixed>
Performs a multi-search query for product listings and processes the results.
getSearchResults()  : SearchResult|null
Factory method to create and return a SearchResult object for the given search term.
getSupportProductListing()  : array<string|int, mixed>
Retrieves a support product listing based on the specified search query.
getSupportProductsMulti()  : array<string|int, mixed>
Performs a multi-search query for support products and processes the results.
getWebsiteAttributes()  : array<string|int, mixed>
Retrieves website attributes based on a specific tag filter.
hasAliasForCollection()  : bool
Checks whether any alias is pointing to the specified collection.
isAliasExists()  : mixed
isBulkMode()  : bool
Whether this request may wait on TypeSense.
isCollectionExists()  : mixed
performMultiSearch()  : array<string|int, mixed>
Performs a multi-search query processes the results.
removeCollectionIfUnused()  : array<string|int, mixed>
Deletes a specific collection if it is not referenced by any alias.
removeOldCollections()  : mixed
removeOldCollectionsWithBackup()  : int
Removes old TypeSense collections that are not used by any alias, while keeping the two most recent versions (based on timestamp suffix) for each logical group.
safeFlushAndRepopulate()  : bool
Safely flushes and populates collections for the specified site.
safeFlushAndRepopulateAllSites()  : bool
Safely flushes and populates collections for all sites (all languages/countries).
saveDataToCollection()  : mixed
Imports documents into a collection.
withWebTimeouts()  : mixed
Runs a callback against the short-timeout client even inside a bulk run.
acquireFlushLock()  : FileLock|null
activeProfile()  : string
buildClient()  : Client
getCachedCollectionMeta()  : array<string|int, mixed>
Retrieves and caches collection metadata from TypeSense.
releaseFlushLock()  : void
throttleWrite()  : void

Constants

PROFILE_BULK

public mixed PROFILE_BULK = 'bulk'

PROFILE_WEB

public mixed PROFILE_WEB = 'web'

WEB_CONNECT_TIMEOUT

private mixed WEB_CONNECT_TIMEOUT = 1.0

WRITE_THROTTLE_US

private mixed WRITE_THROTTLE_US = 500000

Properties

$bulkMode

private static bool $bulkMode = false

$collectionMetaCache

Retrieves the index status of fields in a given collection.

private static array<string|int, mixed> $collectionMetaCache = []

This function connects to the TypeSense client to retrieve metadata about a specific collection and processes the fields to return their indexing status.

  • It skips fields where the name is exactly ".*".
  • If a field name contains the ".*" pattern, the pattern is removed, and the resulting field name is used as the key in the result array.
  • The indexing status of each field is stored in the result array, where the key is the field name (with or without the ".*" pattern) and the value is the field's 'index' status (true or false).

$filterOptionsCache

private static array<string, array<string, array<string|int, string>>> $filterOptionsCache = []

per-request cache of dashboard filter value lists

$forceWebTimeouts

private static bool $forceWebTimeouts = false

$tsClients

private static array<string, Client> $tsClients = []

One client per timeout profile.

Methods

assignAliasToCollection()

Updates or creates an alias for a specific collection.

public static assignAliasToCollection(string $aliasName, string $newCollectionName) : bool

If the alias already exists, it will be updated to point to the new collection.

Parameters
$aliasName : string

The alias name to be updated.

$newCollectionName : string

The name of the new collection to assign to the alias.

Return values
bool —

Returns true on success, false on failure.

deleteAliasByName()

Deletes a specific alias by its name from TypeSense.

public static deleteAliasByName(string $aliasName) : array<string|int, mixed>
Parameters
$aliasName : string

The name of the alias to delete.

Return values
array<string|int, mixed> —

Result of the deletion with 'success' and 'message'.

deleteAllCollectionsAndAliases()

Deletes all aliases and collections from TypeSense.

public static deleteAllCollectionsAndAliases() : array<string|int, mixed>
Return values
array<string|int, mixed> —

Result with success flag and message.

dirtyFlush()

public static dirtyFlush(string $safeFraze) : mixed
Parameters
$safeFraze : string

enterBulkMode()

Marks the rest of this request as a bulk run, so TypeSense gets the long-timeout client. For work that legitimately streams for minutes but does not run under WP-CLI or cron: an admin flush, or the sitemap walking the whole catalogue.

public static enterBulkMode() : void

getAliases()

public static getAliases() : mixed

getAllProductListingProducts()

Retrieves all products from the product listing.

public static getAllProductListingProducts([int $page = 1 ][, int $perPage = 200 ][, array<string|int, mixed> $allProducts = [] ][, array<string|int, mixed> $commonParams = [] ]) : array<string|int, mixed>
Parameters
$page : int = 1
$perPage : int = 200
$allProducts : array<string|int, mixed> = []
$commonParams : array<string|int, mixed> = []
Return values
array<string|int, mixed> —

The search result with ProductCard objects in place of raw product data.

getAllSupportProductListingProducts()

Retrieves all support products from the support listing.

public static getAllSupportProductListingProducts([int $page = 1 ][, int $perPage = 200 ][, array<string|int, mixed> $allProducts = [] ][, array<string|int, mixed> $commonParams = [] ]) : array<string|int, mixed>
Parameters
$page : int = 1
$perPage : int = 200
$allProducts : array<string|int, mixed> = []
$commonParams : array<string|int, mixed> = []
Return values
array<string|int, mixed> —

The search result with ProductCard objects in place of raw product data.

getCollectionDocument()

public static getCollectionDocument(string $id, string $collectionName) : mixed
Parameters
$id : string
$collectionName : string

getCollectionDocuments()

public static getCollectionDocuments(string $collectionName) : mixed
Parameters
$collectionName : string

getCollectionFieldsIndexStatus()

public static getCollectionFieldsIndexStatus(string $collectionName) : array<string|int, mixed>
Parameters
$collectionName : string
Return values
array<string|int, mixed>

getCollectionFilterOptions()

Distinct values for each facetable field of a collection, keyed by the DASHBOARD COLUMN they belong to — so a locale-mapped field like `status` (stored as status.en, status.de, …) reports under `status`, which is the key the filter UI uses.

public static getCollectionFilterOptions(string $collectionName[, int $limit = 50 ]) : array<string, array<string|int, string>>

One facet request covers every facetable field at once: the dashboard renders the whole filter row on each page load, and a request per column would be the page's dominant cost.

A field with more than $limit distinct values is OMITTED rather than truncated — a partial dropdown is worse than a text box, because it silently hides the value you wanted. We ask for $limit + 1 precisely to tell "all of them" from "too many".

Parameters
$collectionName : string
$limit : int = 50
Return values
array<string, array<string|int, string>> —

column key => values

getCollectionObjectFields()

Returns an array of field names that are object type in the given collection.

public static getCollectionObjectFields(string $collectionName) : array<string|int, mixed>

These fields need special handling — they can't use filter_by := but can be searched via their string sub-fields (e.g. name.en, status.de).

Parameters
$collectionName : string
Return values
array<string|int, mixed>

getCollections()

public static getCollections() : mixed

getCollectionSearchableFields()

Returns a comma-separated list of searchable (indexed string-type) field names for a given collection, suitable for TypeSense's `query_by` parameter.

public static getCollectionSearchableFields(string $collectionName) : string
Parameters
$collectionName : string
Return values
string

getCollectionsWithoutAlias()

Returns an array of collections that are not pointed to by any alias.

public static getCollectionsWithoutAlias() : array<string|int, mixed>
Return values
array<string|int, mixed> —

List of collection arrays (as returned by TypeSense) without alias.

getProduct()

Creates and retrieves a Product instance based on the provided slug.

public static getProduct(string $slug) : Product|false

This static method attempts to instantiate a Product with the given parameters. If an exception occurs during instantiation, it logs the exception and returns false.

Parameters
$slug : string

The unique slug for the product.

Return values
Product|false —

Returns a Product instance if successful, or false if products was not found.

getProductById()

Creates and retrieves a Product instance based on the provided ID.

public static getProductById(string $id) : Product|false

This static method attempts to instantiate a Product with the given parameters. If an exception occurs during instantiation, it logs the exception and returns false.

Parameters
$id : string

The unique identifier for the product.

Return values
Product|false —

Returns a Product instance if successful, or false if an exception is caught.

getProductListing()

Retrieves a product listing based on the specified search query.

public static getProductListing(array<string|int, mixed> $searchQuery) : array<string|int, mixed>

This method performs a search in the ListingCollection and processes the results. For each search result, it creates a ProductCard using the product's ID and card data. Any errors encountered during the creation of ProductCard instances are logged. The modified search results, with ProductCard objects replacing the raw data, are returned.

Parameters
$searchQuery : array<string|int, mixed>

The search parameters used to query the product listing.

Return values
array<string|int, mixed> —

The search result with ProductCard objects in place of raw product data.

getProductListingMulti()

Performs a multi-search query for product listings and processes the results.

public static getProductListingMulti(array<string|int, mixed> $searchRequests[, array<string|int, mixed> $commonParams = [] ]) : array<string|int, mixed>

This method sends multiple search requests and processes the main search result, which is always the first result in the multi-search. It reindexes facet counts, creates ProductCard objects for each hit in the main result, and merges additional facet data from side queries back into the main result.

It also ensures that all missing facets from the complete product set are added to the main result by performing an additional search for all facets and merging any missing facets with the filtered ones.

Parameters
$searchRequests : array<string|int, mixed>

An array of search requests to be performed.

$commonParams : array<string|int, mixed> = []

Common parameters to be applied to all search requests.

Return values
array<string|int, mixed> —

The processed main result, including hits and facet counts.

getSearchResults()

Factory method to create and return a SearchResult object for the given search term.

public static getSearchResults(string $searchTerm, int $page[, int $perPage = 20 ]) : SearchResult|null
Parameters
$searchTerm : string

The term to search for.

$page : int

The page number to search for.

$perPage : int = 20

The number of results per page.

Return values
SearchResult|null —

The SearchResult object containing the search results for the provided term.

getSupportProductListing()

Retrieves a support product listing based on the specified search query.

public static getSupportProductListing(array<string|int, mixed> $searchQuery) : array<string|int, mixed>

This method performs a search in the SupportCollection and processes the results. For each search result, it creates a ProductCard using the product's ID and card data. Any errors encountered during the creation of ProductCard instances are logged. The modified search results, with ProductCard objects replacing the raw data, are returned.

Parameters
$searchQuery : array<string|int, mixed>

The search parameters used to query the product listing.

Return values
array<string|int, mixed> —

The search result with ProductCard objects in place of raw product data.

getSupportProductsMulti()

Performs a multi-search query for support products and processes the results.

public static getSupportProductsMulti(array<string|int, mixed> $searchRequests[, array<string|int, mixed> $commonParams = [] ]) : array<string|int, mixed>

This method sends multiple search requests and processes the main search result, which is always the first result in the multi-search. It reindexes facet counts, creates ProductCard objects for each hit in the main result, and merges additional facet data from side queries back into the main result.

It also ensures that all missing facets from the complete product set are added to the main result by performing an additional search for all facets and merging any missing facets with the filtered ones.

Parameters
$searchRequests : array<string|int, mixed>

An array of search requests to be performed.

$commonParams : array<string|int, mixed> = []

Common parameters to be applied to all search requests.

Return values
array<string|int, mixed> —

The processed main result, including hits and facet counts.

getWebsiteAttributes()

Retrieves website attributes based on a specific tag filter.

public static getWebsiteAttributes() : array<string|int, mixed>

This function searches for attributes using a wildcard query and filters the results by a specific tag obtained from the configuration.

It returns an array of attributes, where each attribute includes:

  • 'id': The pretty ID of the document, or an empty string if not available.
  • 'name': The name of the document, or an empty string if not available.
Return values
array<string|int, mixed> —

An array of attributes, each containing 'id' and 'name'.

hasAliasForCollection()

Checks whether any alias is pointing to the specified collection.

public static hasAliasForCollection(string $collectionName) : bool
Parameters
$collectionName : string

The name of the collection to check.

Return values
bool —

True if any alias points to the given collection, false otherwise.

isAliasExists()

public static isAliasExists(string $alias) : mixed
Parameters
$alias : string

isBulkMode()

Whether this request may wait on TypeSense.

public static isBulkMode() : bool
Return values
bool

isCollectionExists()

public static isCollectionExists(mixed $collectionName) : mixed
Parameters
$collectionName : mixed

performMultiSearch()

Performs a multi-search query processes the results.

public static performMultiSearch(string $collectionAllias, array<string|int, mixed> $searchRequests[, array<string|int, mixed> $commonParams = [] ]) : array<string|int, mixed>

This method sends multiple search requests and processes the main search result, which is always the first result in the multi-search. It reindexes facet counts, creates ProductCard objects for each hit in the main result, and merges additional facet data from side queries back into the main result.

It also ensures that all missing facets from the complete product set are added to the main result by performing an additional search for all facets and merging any missing facets with the filtered ones.

Parameters
$collectionAllias : string
$searchRequests : array<string|int, mixed>

An array of search requests to be performed.

$commonParams : array<string|int, mixed> = []

Common parameters to be applied to all search requests.

Return values
array<string|int, mixed> —

The processed main result, including hits and facet counts.

removeCollectionIfUnused()

Deletes a specific collection if it is not referenced by any alias.

public static removeCollectionIfUnused(string $collectionName) : array<string|int, mixed>
Parameters
$collectionName : string

The name of the collection to delete.

Return values
array<string|int, mixed> —

An array containing:

  • 'success' (bool): true if deleted, false otherwise
  • 'message' (string): status or error message

removeOldCollections()

public static removeOldCollections() : mixed

removeOldCollectionsWithBackup()

Removes old TypeSense collections that are not used by any alias, while keeping the two most recent versions (based on timestamp suffix) for each logical group.

public static removeOldCollectionsWithBackup() : int

A collection is considered part of the same group if it shares the same prefix (i.e., everything before the last two parts – datetime and timestamp).

This method helps retain recent backups in case a new index build fails.

Return values
int —

Number of deleted collections.

safeFlushAndRepopulate()

Safely flushes and populates collections for the specified site.

public static safeFlushAndRepopulate([int|null $blogId = null ][, array<string|int, mixed> $options = [] ]) : bool

This function ensures that all necessary collections are populated for a single site. Global collections (Attributes, Products, ExternalProducts) are still generated once, but the rest are site-scoped and use the provided blog ID for locale/country/brand context.

Parameters
$blogId : int|null = null
$options : array<string|int, mixed> = []

Optional flags: skip_attributes, skip_products, skip_external_products.

Return values
bool

safeFlushAndRepopulateAllSites()

Safely flushes and populates collections for all sites (all languages/countries).

public static safeFlushAndRepopulateAllSites([array<string|int, mixed> $options = [] ]) : bool

This function first updates global collections (Attributes, Products, ExternalProducts), then loops through all sites and populates site-specific collections (Product Groups, Product Cards, Listings, Search, Support). Use "site_ids" in $options to target a subset of sites.

Parameters
$options : array<string|int, mixed> = []
Return values
bool

saveDataToCollection()

Imports documents into a collection.

public static saveDataToCollection(array<string|int, mixed> $data, string $collectionName[, bool $logProgress = true ][, string $action = 'create' ][, array<string|int, mixed>|null &$importInfo = null ]) : mixed

$action defaults to 'create' so a rebuild into a fresh collection still rejects — and therefore reports — a duplicate id, which there can only mean bad source data. Writers that target the LIVE aliased collection pass 'upsert' instead: for them a repeat id is the normal case, not a fault.

Returns the number of documents that were actually written, so a falsy return means NOTHING landed. That is not the same as "everything landed": callers that go on to publish the collection (an alias swap) must read $importInfo['lost_count'] — see populateCollection.

Parameters
$data : array<string|int, mixed>
$collectionName : string
$logProgress : bool = true
$action : string = 'create'

TypeSense import action: 'create' or 'upsert'.

$importInfo : array<string|int, mixed>|null = null

Out-param: the full success/error/lost breakdown.

withWebTimeouts()

Runs a callback against the short-timeout client even inside a bulk run.

public static withWebTimeouts(callable $callback) : mixed

Timeouts and bulk semantics are separate concerns: a settings lookup is a small document GET on the critical path of every context, so it must never inherit the import ceiling. Without this, one unreachable node made every wp command sleep through the retry backoff before WordPress had finished booting.

Parameters
$callback : callable

activeProfile()

private static activeProfile() : string
Return values
string

buildClient()

private static buildClient(string $profile) : Client
Parameters
$profile : string
Return values
Client

getCachedCollectionMeta()

Retrieves and caches collection metadata from TypeSense.

private static getCachedCollectionMeta(string $collectionName) : array<string|int, mixed>

Avoids duplicate API calls when multiple methods need the same metadata.

Parameters
$collectionName : string
Return values
array<string|int, mixed>

throttleWrite()

private static throttleWrite() : void
On this page

Search results