> 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

# QueryDataItems

# Package: externalDatabases

# Namespace: ExternalDatabaseService

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

## Introduction

Retrieves a list of items based on the provided filtering, sorting, and paging preferences.

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: queryDataItems
 Description: Retrieves a list of items based on the provided filtering, sorting, and paging preferences.  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
 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, query, query.filter, 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: includeReferencedItems | type: array<includeReferencedItems> | description: Fields for which to include the full referenced items in the query's results, rather than just their GUIDs. Returned items are sorted in ascending order by the creation date of the reference. If the field being querried is a multi-reference field and the array is empty, the response does not return any items.  
              - name: fieldKey | type: string | description: Field name in the referencing collection.  
              - name: limit | type: integer | description: Maximum number of referenced items to return.  
              - name: filter | type: object | description: Filter criteria to specify which items to include in the response.  
   param name: query | type: QueryV2   | required: true 
    - ONE-OF: - required: true
     - name: paging | type: Paging | description: Paging options to limit and skip the number of items. Paging mode is defined when the collection is created.  
        - 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: Cursor token pointing to a page of results. Not used in the first request. Following requests use the cursor token and not `filter` or `sort`. Paging mode is defined when the collection is created.  
        - 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: filter | type: object | description: Filter object in the following format: `"filter" : { "fieldName1": "value1", "fieldName2":{"$operator":"value2"} }` Example of operators: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$hasSome`, `$hasAll`, `$startsWith`, `$contains`  **Note:** Your endpoint must properly handle requests with filtering preferences that adhere to Wix Data data types. For example, a query request that includes filtering by a field whose type is Date and Time would contain an object in the following format: `"someDateAndTimeFieldKey": { "$date": "YYYY-MM-DDTHH:mm:ss.sssZ"}`. Learn more about [data types in Wix Data](https://dev.wix.com/docs/rest/business-solutions/cms/data-items/data-types-in-wix-data.md). | required: true 
        - name: sort | type: array<Sorting> | description: Sort object in the following format: `[{"fieldName":"sortField1","order":"ASC"},{"fieldName":"sortField2","order":"DESC"}]`  
           - name: fieldName | type: string | description: Name of the field to sort by.  
           - name: order | type: SortOrder | description: Sort order.  
                 - enum: ASC, DESC
        - name: fields | type: array<string> | description: Array of projected fields. A list of specific field names to return.  
   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: QueryDataItemsResponse
  - name: items | type: array | description: Retrieved items.  
  - name: pagingMetadata | type: PagingMetadataV2 | description: Pagination 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.  

 Possible Errors:
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: BAD_REQUEST | Description: The request is invalid.
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: COLLECTION_CHANGE_NOT_SUPPORTED | Description: The collection field can't be changed.
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: VALIDATION_ERROR | Description: 1 or more field values are invalid.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: REFERENCE_NOT_FOUND | Description: Couldn't find the reference.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: COLLECTION_NOT_FOUND | Description: Couldn't find the collection.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: ITEM_NOT_FOUND | Description: Couldn't find the item.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: REFERENCE_ALREADY_EXISTS | Description: There is already a reference between these items.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: COLLECTION_ALREADY_EXISTS | Description: There is already a collection with this GUID.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: ITEM_ALREADY_EXISTS | Description: There is already an item with this GUID.


```

### Examples

### Complex query
A query with filtering requirements, sorting preferences, and the fields and referenced items to include.

```curl
curl -X POST https://external-db.example.com/v3/items/query  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "query": {
    "filter": {
      "$or": [{
        "$and": [{
          "name": {
            "$startsWith": "New"
          }
        }, {
          "population": {
            "$gt": 1000000.0
          }
        }]
      }, {
        "$and": [{
          "isCapital": true
        }, {
          "_updatedDate": {
            "$gt": {
              "$date": "2021-01-01T00:00:00Z"
            }
          }
        }, {
          "$not": {
            "name": {
              "$startsWith": "New"
            }
          }
        }]
      }]
    },
    "sort": [{
      "fieldName": "country",
      "order": "ASC"
    }, {
      "fieldName": "name",
      "order": "DESC"
    }],
    "paging": {
      "limit": 50,
      "offset": 0
    },
    "fields": ["name", "_id", "population", "myTrips", "_updatedDate", "pointsOfInterest"]
  },
  "includeReferencedItems": [{
    "fieldKey": "pointsOfInterest",
    "limit": 50
  }, {
    "fieldKey": "myTrips",
    "limit": 50,
    "filter": {
      "_owner": "6785b759-eeb3-4709-ac3c-91013d82690c"
    }
  }],
  "consistentRead": false,
  "returnTotalCount": false
}'
```

### Query with cursor information
For collections that support cursor pagination, a cursor is provided for the second page and onwards.

```curl
curl -X POST https://external-db.example.com/v3/items/query  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "query": {
    "filter": {
    },
    "sort": [],
    "fields": [],
    "cursorPaging": {
      "limit": 2,
      "cursor": "ImtpZCI6ImEz"
    }
  },
  "includeReferencedItems": [],
  "consistentRead": false,
  "returnTotalCount": false
}'
```

### Query a single data item by ID
Queries a single data item using a filter with an `_id` field.

```curl
curl -X POST https://external-db.example.com/v3/items/query  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "query": {
    "filter": {
      "_id": "c285e77c-a86b-4361-a55f-c6b934d70187"
    },
    "sort": [],
    "paging": {
      "limit": 1,
      "offset": 0
    },
    "fields": []
  },
  "includeReferencedItems": [],
  "consistentRead": false,
  "returnTotalCount": false
}'
```

### Query data items
```curl
curl -X POST https://external-db.example.com/v3/items/query  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "query": {
    "filter": {
    },
    "sort": [],
    "paging": {
      "limit": 50,
      "offset": 0
    },
    "fields": []
  },
  "includeReferencedItems": [],
  "consistentRead": false,
  "returnTotalCount": true
}'
```

---

## JavaScript SDK

### Schema

```
 Method: wixClientAdmin.data.externalDatabase.queryDataItems(request, metadata)
 Description: Retrieves a list of items based on the provided filtering, sorting, and paging preferences.  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: QueryDataItemsRequest    
        - name: collectionId | type: string | description: GUID of the collection to query.  
        - name: query | type: QueryV2 | description: Query preferences. See [API Query Language](https://dev.wix.com/api/rest/getting-started/api-query-language) for information about handling data queries.  
           - ONE-OF: 
              - name: paging | type: Paging | description: Paging options to limit and skip the number of items. Paging mode is defined when the collection is created.  
                 - 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: Cursor token pointing to a page of results. Not used in the first request. Following requests use the cursor token and not `filter` or `sort`. Paging mode is defined when the collection is created.  
                 - 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: filter | type: object | description: Filter object in the following format: `"filter" : { "fieldName1": "value1", "fieldName2":{"$operator":"value2"} }` Example of operators: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$hasSome`, `$hasAll`, `$startsWith`, `$contains`  **Note:** Your endpoint must properly handle requests with filtering preferences that adhere to Wix Data data types. For example, a query request that includes filtering by a field whose type is Date and Time would contain an object in the following format: `"someDateAndTimeFieldKey": { "$date": "YYYY-MM-DDTHH:mm:ss.sssZ"}`. Learn more about [data types in Wix Data](https://dev.wix.com/docs/rest/business-solutions/cms/data-items/data-types-in-wix-data.md).  
           - name: sort | type: array<Sorting> | description: Sort object in the following format: `[{"fieldName":"sortField1","order":"ASC"},{"fieldName":"sortField2","order":"DESC"}]`  
              - name: fieldName | type: string | description: Name of the field to sort by.  
              - name: order | type: SortOrder | description: Sort order.  
                     - enum: ASC, DESC
           - name: fields | type: array<string> | description: Array of projected fields. A list of specific field names to return.  
        - name: includeReferencedItems | type: array<ReferencedItemToInclude> | description: Fields for which to include the full referenced items in the query's results, rather than just their GUIDs. Returned items are sorted in ascending order by the creation date of the reference. If the field being querried is a multi-reference field and the array is empty, the response does not return any items.  
           - name: fieldKey | type: string | description: Field name in the referencing collection.  
           - name: limit | type: integer | description: Maximum number of referenced items to return.  
           - name: filter | type: object | description: Filter criteria to specify which items to include in the response.  
        - 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<QueryDataItemsResponse>
  - name: items | type: array | description: Retrieved items.  
  - name: pagingMetadata | type: PagingMetadataV2 | description: Pagination 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.  

 Possible Errors:
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: BAD_REQUEST | Description: The request is invalid.
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: COLLECTION_CHANGE_NOT_SUPPORTED | Description: The collection field can't be changed.
   HTTP Code: 400 | Status Code: INVALID_ARGUMENT | Application Code: VALIDATION_ERROR | Description: 1 or more field values are invalid.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: REFERENCE_NOT_FOUND | Description: Couldn't find the reference.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: COLLECTION_NOT_FOUND | Description: Couldn't find the collection.
   HTTP Code: 404 | Status Code: NOT_FOUND | Application Code: ITEM_NOT_FOUND | Description: Couldn't find the item.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: REFERENCE_ALREADY_EXISTS | Description: There is already a reference between these items.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: COLLECTION_ALREADY_EXISTS | Description: There is already a collection with this GUID.
   HTTP Code: 409 | Status Code: ALREADY_EXISTS | Application Code: ITEM_ALREADY_EXISTS | Description: There is already an item with this GUID.


```

### Examples

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

externalDatabase.provideHandlers({

  queryDataItems: 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:
        items: [
          {
            name: "New York",
            _id: "c285e77c-a86b-4361-a55f-c6b934d70187",
            population: 8300000.0,
            country: "US",
            isCapital: false
          }
        ],
        pagingMetadata: {
          total: 1
        }
      }
    }
});

```

### queryDataItems (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 queryDataItems(request,metadata) {
  const response = await myWixClient.externalDatabase.queryDataItems(request,metadata);
};
```

---