> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

# QueryDistinctValues

# Package: externalDatabases

# Namespace: ExternalDatabaseService

# Method link: https://dev.wix.com/docs/api-reference/business-solutions/cms/external-databases/external-database-service-plugin/query-distinct-values.md

## Introduction

Retrieves a list of distinct values for a given field for all items that match the query, without duplicates.


As with the [Query Data Items](https://dev.wix.com/docs/rest/assets/data/external-database-spi/query-data-items.md) endpoint, this endpoint retrieves items based on the filtering, sorting, and paging preferences provided.
However, the Query Distinct Values endpoint doesn't return the full items that match the query. Rather, for items that match the query, it returns all unique values in the field specified in `fieldName`. If more than one item has the same value in that field, that value appears only once.

See [API Query Language](https://dev.wix.com/api/rest/getting-started/api-query-language) for more information about handling data queries.

---

## REST API

### Schema

```
 Method: queryDistinctValues
 Description: Retrieves a list of distinct values for a given field for all items that match the query, without duplicates.   As with the [Query Data Items](https://dev.wix.com/docs/rest/assets/data/external-database-spi/query-data-items.md) endpoint, this endpoint retrieves items based on the filtering, sorting, and paging preferences provided. However, the Query Distinct Values endpoint doesn't return the full items that match the query. Rather, for items that match the query, it returns all unique values in the field specified in `fieldName`. If more than one item has the same value in that field, that value appears only once.  See [API Query Language](https://dev.wix.com/api/rest/getting-started/api-query-language) for more information about handling data queries.
 URL: {DEPLOYMENT-URI}/v3/items/query-distinct-values
 Method: POST
 # Note: If the parameter `a.b` is listed under required parameters, `b` is only required if `a` is also present.
 Required parameters:  collectionId, fieldName, consistentRead, returnTotalCount
 Method parameters: 
   param name: collectionId | type: collectionId | description: GUID of the collection to query. | required: true 
   param name: consistentRead | type: consistentRead | description: Whether to retrieve data from the primary database instance. This decreases performance but ensures data retrieved is up-to-date even immediately after an update. Applicable if the external database is eventually consistent. | required: true 
   param name: fieldName | type: fieldName | description: Item field name for which to return all distinct values. | required: true 
   param name: filter | type: filter | description: Filter to apply to the collection's data before aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
   param name: order | type: SortOrder    
      - enum:
           ASC - 
           DESC - 
    - ONE-OF: 
     - name: paging | type: Paging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, format int32
        - name: offset | type: integer | description: Number of items to skip in the current sort order.  | validation: minimum 0, format int32
     - name: cursorPaging | type: CursorPaging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, maximum 1000, format int32
        - name: cursor | type: string | description: Pointer to the next or previous page in the list of results.  You can get the relevant cursor token from the `pagingMetadata` object in the previous call's response. Not relevant for the first request.  
   param name: returnTotalCount | type: returnTotalCount | description: When `true`, the query response must include the total number of items that match the query. | required: true 
 Return type: QueryDistinctValuesResponse
  - name: distinctValues | type: array<Value> | description: List of distinct values contained in the field specified in `fieldName`. Values can be of any JSON type. If the field is an array, values must be unwound, independent values. For example, if the field name contains `["a", "b", "c"]`, the result must contain `"a"`, `"b"` and `"c"` as separate values.  
     - ONE-OF: 
        - name: nullValue | type:  | description:   
        - name: numberValue | type: number | description:   
        - name: stringValue | type: string | description:   
        - name: boolValue | type: boolean | description:   
        - name: structValue | type: object | description:   
        - name: listValue | type: ListValue | description:   
           - name: values | type: array<Value> | description:   
  - name: pagingMetadata | type: PagingMetadataV2 | description: Paging information.  
     - name: total | type: integer | description: Total number of items that match the query. Returned if offset paging is used and the `tooManyToCount` flag is not set.  | validation: format int32
     - name: cursors | type: Cursors | description: Cursors to navigate through the result pages using `next` and `prev`. Returned if cursor paging is used.  
        - name: next | type: string | description: Cursor pointing to next page in the list of results.  
        - name: prev | type: string | description: Cursor pointing to previous page in the list of results.  


```

### Examples

### Query distinct values with filtering
Data items are filtered before retrieving distinct values.

```curl
curl -X POST https://external-db.example.com/v3/items/query-distinct-values  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "filter": {
    "isCapital": true
  },
  "fieldName": "country",
  "order": "ASC",
  "paging": {
    "limit": 50,
    "offset": 0
  },
  "consistentRead": false,
  "returnTotalCount": true
}'
```

### Query distinct values
```curl
curl -X POST https://external-db.example.com/v3/items/query-distinct-values  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "fieldName": "country",
  "order": "ASC",
  "paging": {
    "limit": 50,
    "offset": 0
  },
  "consistentRead": false,
  "returnTotalCount": false
}'
```

---

## JavaScript SDK

### Schema

```
 Method: wixClientAdmin.data.externalDatabase.queryDistinctValues(request, metadata)
 Description: Retrieves a list of distinct values for a given field for all items that match the query, without duplicates.   As with the [Query Data Items](https://dev.wix.com/docs/rest/assets/data/external-database-spi/query-data-items.md) endpoint, this endpoint retrieves items based on the filtering, sorting, and paging preferences provided. However, the Query Distinct Values endpoint doesn't return the full items that match the query. Rather, for items that match the query, it returns all unique values in the field specified in `fieldName`. If more than one item has the same value in that field, that value appears only once.  See [API Query Language](https://dev.wix.com/api/rest/getting-started/api-query-language) for more information about handling data queries.
 Method parameters:
   param name: request | type: QueryDistinctValuesRequest    
    - ONE-OF: 
     - name: paging | type: Paging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, format int32
        - name: offset | type: integer | description: Number of items to skip in the current sort order.  | validation: minimum 0, format int32
     - name: cursorPaging | type: CursorPaging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, maximum 1000, format int32
        - name: cursor | type: string | description: Pointer to the next or previous page in the list of results.  You can get the relevant cursor token from the `pagingMetadata` object in the previous call's response. Not relevant for the first request.  
        - name: collectionId | type: string | description: GUID of the collection to query.  
        - name: filter | type: object | description: Filter to apply to the collection's data before aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
        - name: fieldName | type: string | description: Item field name for which to return all distinct values.  
        - name: order | type: SortOrder | description: Order to by which to sort the results. Valid values are `ASC` and `DESC`.  
             - enum: ASC, DESC
        - name: consistentRead | type: boolean | description: Whether to retrieve data from the primary database instance. This decreases performance but ensures data retrieved is up-to-date even immediately after an update. Applicable if the external database is eventually consistent.  
        - name: returnTotalCount | type: boolean | description: When `true`, the query response must include the total number of items that match the query.  
   param name: metadata | type: Context | description: this message is not directly used by any service, it exists to describe the expected parameters that SHOULD be provided to invoked Velo methods as part of open-platform. e.g. SPIs, event-handlers, etc.. NOTE: this context object MUST be provided as the last argument in each Velo method signature.  Example: ```typescript export function wixStores_onOrderCanceled({ event, metadata }: OrderCanceledEvent) { ... } ```  
        - name: requestId | type: string | description: A unique identifier of the request. You may print this GUID to your logs to help with future debugging and easier correlation with Wix's logs.  
        - name: currency | type: string | description: [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) 3-letter currency code.  | validation: format CURRENCY
        - name: identity | type: IdentificationData | description: An object that describes the identity that triggered this request.  
           - ONE-OF: 
              - name: anonymousVisitorId | type: string | description: GUID of a site visitor that has not logged in to the site.  | validation: format GUID
              - name: memberId | type: string | description: GUID of a site visitor that has logged in to the site.  | validation: format GUID
              - name: wixUserId | type: string | description: GUID of a Wix user (site owner, contributor, etc.).  | validation: format GUID
              - name: appId | type: string | description: GUID of an app.  | validation: format GUID
        - name: languages | type: array<string> | description: A string representing a language and region in the format of `"xx-XX"`. First 2 letters represent the language code according to ISO 639-1. This is followed by a dash "-", and then a by 2 capital letters representing the region according to ISO 3166-2. For example, `"en-US"`.  
        - name: instanceId | type: string | description: The service provider app's instance GUID.  | validation: format GUID
 Return type: PROMISE<QueryDistinctValuesResponse>
  - name: distinctValues | type: array<Value> | description: List of distinct values contained in the field specified in `fieldName`. Values can be of any JSON type. If the field is an array, values must be unwound, independent values. For example, if the field name contains `["a", "b", "c"]`, the result must contain `"a"`, `"b"` and `"c"` as separate values.  
     - ONE-OF: 
        - name: nullValue | type:  | description:   
        - name: numberValue | type: number | description:   
        - name: stringValue | type: string | description:   
        - name: boolValue | type: boolean | description:   
        - name: structValue | type: object | description:   
        - name: listValue | type: ListValue | description:   
           - name: values | type: array<Value> | description:   
  - name: pagingMetadata | type: PagingMetadataV2 | description: Paging information.  
     - name: total | type: integer | description: Total number of items that match the query. Returned if offset paging is used and the `tooManyToCount` flag is not set.  | validation: format int32
     - name: cursors | type: Cursors | description: Cursors to navigate through the result pages using `next` and `prev`. Returned if cursor paging is used.  
        - name: next | type: string | description: Cursor pointing to next page in the list of results.  
        - name: prev | type: string | description: Cursor pointing to previous page in the list of results.  


```

### Examples

### Example of `distinctValues` and `pagingMetadata` return values
```javascript
import { externalDatabase } from '@wix/data/service-plugins';

externalDatabase.provideHandlers({

  queryDistinctValues: async ( payload ) => {
    const {request, metadata} = payload;
        // Use the `request` and `metadata` received from Wix and
        // apply custom logic.
      return {
        // Return your response exactly as documented to integrate with Wix.
        // Return value example:
        distinctValues: ["US", "CA"],
        pagingMetadata: {}
      }
    }
});

```

### queryDistinctValues (self-managed)
Self-managed SDK calls require you to [create a client](https://dev.wix.com/docs/sdk/articles/work-with-the-sdk/about-the-wix-client.md).

```javascript
import { createClient } from '@wix/sdk';
import { externalDatabase } from '@wix/data/service-plugins';
// Import the auth strategy for the relevant access type
// Import the relevant host module if needed

const myWixClient = createClient ({
  modules: { externalDatabase },
  // Include the auth strategy and host as relevant
});


async function queryDistinctValues(request,metadata) {
  const response = await myWixClient.externalDatabase.queryDistinctValues(request,metadata);
};
```

---