
[space] Klevu

[title] Developer
[path] /

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/UB8Fl_E5rwCkg-Fa4p9Wq_klevu-developers-logo-blue.png)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/fYg3qymZ7yCYPGuCs5Gum_klevu-developer-landing-banner.jpg)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/C_R_2cmPWpT_TX4wIO9H-_klevu-icon-api-reference.jpg)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/KGNxohi-biV5gUm3Ji5ve_klevu-icon-js-library.jpg)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/zQw-HGfdvMD3EaK9n4gRx_klevu-icon-headless.png)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/zAI147X2wCml6hZsv3AI__klevu-icon-xml.jpg)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/wL3P_S2Wfz9g7OzW_eQgp_klevu-icon-community-forum.jpg)

::File{src="https://archbee-doc-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/w0uOL7018sjNZ-g-oYEA7_bootstrapmin.css" label="bootstrap.min.css" uploadAsPublic="false"}

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/v_DhXfkwsQltM51ormdZq_dataindexing.png)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/Ed77yGo1Ho8qGs4o9xE_R_vdhxfkwsqltm51ormdzqdataindexing.png)



![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-SPNXOIMQisaCn8oaw3Odr-20240920-095407.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-nauSwUTpDSkS50RZgL8NB-20240920-095548.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-XVB_X7u1sIf9MMpKH1Gnk-20240920-095630.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-0NNiwIm2SfIer42liTh_z-20240920-095654.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-Tw3UrM1HkXwj0SMiTGDg1-20240920-095715.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-SK1vTbbAzIiDY_HNF2lc7-20240920-095733.svg)

![](https://archbee-image-uploads.s3.amazonaws.com/OnatEUfOFbxnahm52lqr_-4ugLHuiw3-0v2uCdm4_P8-20240923-104304.svg)


[space] Storefront APIs (/apis)

[title] Analytics Tracking
[path] Guide/

## Overview

Reporting user interaction with Klevu is crucial to allow the machine learning algorithms to accurately rank items.&#x20;

Analytics should be considered a required component of implementation. 

There are three key aspects of analytic reporting:&#x20;

1. **Searches** : the primary source of learning, and is where we ascertain the most meaningful and useful customer interactions.&#x20;
2. **Clicks** : a machine learning data point measuring engagement.&#x20;
3. **Purchases** : are a critical data point for attributing conversion.&#x20;

These learnings are applied to all three of our core products: Search, Category Merchandising and Recommendations. Including all enabled banners and facets.

:::hint{type="warning"}
In most of the analytic calls, the **shopper's IP address** is used by the machine learning to attribute a single shopper's *searches* and *clicks* into *conversions*.

Please note: If the `klevu_shopperIP` parameter is left empty, Klevu will attempt to retrieve the IP value from the header of the request itself.  As best practice, when possible, you should identify the IP value prior to the analytics call and consider it as a required parameter.&#x20;
:::

## Analytics URL

The endpoint urls are based on your assigned Analytics URL. You can find this value within your Klevu Merchant Center dashboard.

***Klevu Merchant Center > Store Settings > Analytics URL***

You will see this represented in the documentation as placeholder `{{ Analytics_URL }}`

## Request Headers

When proxying analytics calls to our system, ensure that all common request headers, including the original `User-Agent`, are passed through correctly.&#x20;

This is crucial for accurate reporting, as our system relies on standard headers to derive important information such as .

We don’t provide specific guidelines for individual header values, as browsers and HTTP clients send predefined values. However, it’s important to handle these headers correctly. For more details on common request headers, refer to [Mozilla Developer Network's Glossary on Request Headers](https://developer.mozilla.org/en-US/docs/Glossary/Request_header).


[title] Klaviyo : Segmentation
[path] Guide/Connectors/

The following guide will walk you through accessing Klevu Smart Recommendation configurations and applying corresponding pre-configured segments to web visitors via the Klevu API.

:::hint{type="warning"}
To implement Klaviyo segmentation logic with Klevu Smart Recommendations, you need an active subscription to Klaviyo and Klevu Smart Recommendations (with Personalization enabled).
:::



The intitial setup and configuration process takes place within the Klevu Merchant Center. Detailed instructions on how to integrate Klaviyo with Klevu Smart Recommendations can be found [here](https://help.klevu.com/support/solutions/articles/5000884090-create-recommendation-banner-with-segments).

**There are four key steps to consider:**
1\. Fetch the applicable segments for the visitor
2\. Apply the Segments to the Recommendations configuration
3\. Request and display the Klevu Recommendations banner
4\. Collect Klevu Analytics (impressions and interaction)



# 1. Fetch the Applicable Segments for the Visitor

Three parameters are necessary to obtain the appropriate visitor segments&#x20;
1\. Klevu API KEY
2\. Klevu Session ID
3\. Klaviyo Exchange ID

:::hint{type="info"}
Once th&#x65;**&#x20;Klevu Session ID&#x20;**&#x61;nd the **Klaviyo Exchange ID** have been obtained, they can be stored locally and used in subsequent calls to Klevu for recommendations.
:::

:::ApiMethodV2
```json
{
  "name": "Request Session ID ",
  "method": "POST",
  "url": "https://visitor.service.ksearchnet.com/public/1.0/<KLEVU_API_KEY>/session",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "wmVxgdUkTHR5UU6QKxZM-",
        "language": "json",
        "code": "{\"apiKey\":\"<KLEVU_API_KEY>\"}\n",
        "customLabel": "Request Body"
      }
    ],
    "selectedLanguageId": "wmVxgdUkTHR5UU6QKxZM-"
  },
  "results": {
    "languages": [
      {
        "id": "K6b5-HvEEEnE9ck5mPSaM",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"apikey\": \"<KLEVU_API_KEY>\",\n    \"sessionId\": \"<KLEVU_SESSION_ID>\",\n    \"segmentInfo\": {\n        \"segments\": [],\n        \"ttl\": 3600\n    }\n}"
      }
    ],
    "selectedLanguageId": "K6b5-HvEEEnE9ck5mPSaM"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "name": "apiKey",
        "kind": "required",
        "type": "string",
        "description": "The unique Klevu apiKey ID of the store"
      }
    ],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "request-session-id",
  "legacyHash": "6j8bv0MQ-uKYIsHF8aepi"
}
```
:::

:::hint{type="info"}
Retain the sessionId value for this user for use in subsequent API calls to Klevu for a maximum of the ttl time.  At this point refresh the sessionId so as to retain continuity.
:::

###

### Obtain Klaviyo Exchange ID

Klaviyo holds identity and tracking information in a local browser cookie. The exchange\_id is an encrypted identifier for a Klaviyo profile ID. The value is commonly stored within the base64 encoded Klaviyo cookie “\_\_kla\_id”

More information can be found on the Klaviyo developer's website:

- [Understanding cookies in Klaviyo | Klaviyo Help Center](https://help.klaviyo.com/hc/en-us/articles/360034666712)&#x20;
- [Klaviyo Developers](https://developers.klaviyo.com/en/v1-2/reference/exchange)&#x20;

:::hint{type="info"}
Retain the $exchange\_id value for this user for use in subsequent API calls to Klevu.
:::

###

### Obtain Applicable Visitor Segments

Use the *session* endpoint to push the Klaviyo **exchangeID** to Klevu. This will allow Klevu to communicate with Klaviyo directly and return the visitor's applied segmentation.

:::ApiMethodV2
```json
{
  "name": "Request Segments",
  "method": "POST",
  "url": "https://visitor.service.ksearchnet.com/public/1.0/<KLEVU_API_KEY>/session",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "WSX4qj-F_MmV8ie6s0rbA",
        "language": "json",
        "code": "{\n\t\"apiKey\": \"<KLEVU_API_KEY>\",\n\t\"sessionId\": \"<KLEVU_SESSION_ID>\",\n\t\"sessionInfo\": {\n\t\t\"connectorInfo\": [\n\t\t\t{\n\t\t\t\t\"connectorType\": \"klaviyo\",\n\t\t\t\t\"exchangeId\": \"<KLAVIYO_EXCHANGE_ID>\"\n\t\t\t}\n\t\t]\n\t}\n}",
        "customLabel": "Request Body"
      }
    ],
    "selectedLanguageId": "WSX4qj-F_MmV8ie6s0rbA"
  },
  "results": {
    "languages": [
      {
        "id": "MV91_VdMstn2yj9vbd2SY",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"apikey\": \"<KLEVU_API_KEY>\",\n    \"sessionId\": \"<KLEVU_SESSION_ID>\",\n    \"segmentInfo\": {\n        \"segments\": [\n            \"<SEGMENT_ID_A>\",\n            \"<SEGMENT_ID_B>\",\n            \"<SEGMENT_ID_C>\"\n        ],\n        \"ttl\": 173\n    }\n}"
      }
    ],
    "selectedLanguageId": "MV91_VdMstn2yj9vbd2SY"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "name": "apiKey",
        "kind": "required",
        "type": "string",
        "description": "The unique Klevu apiKey ID of the store"
      },
      {
        "name": "sessionId",
        "kind": "required",
        "type": "string",
        "description": "The session ID as obtained in the previous requests",
        "children": []
      },
      {
        "name": "sessionInfo",
        "kind": "required",
        "type": "string",
        "description": "Used to pass details of the session",
        "children": []
      },
      {
        "name": "connectorInfo",
        "kind": "required",
        "type": "string",
        "description": "Used to pass details of the applied connector",
        "children": []
      },
      {
        "name": "connectorType",
        "kind": "required",
        "type": "string",
        "description": "The value should be \"klaviyo\" in this context",
        "children": []
      },
      {
        "name": "exchangeId",
        "kind": "required",
        "type": "string",
        "description": "The vlaue of the Klaviyo exchangeID as previously obtained",
        "children": []
      }
    ],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "request-segments",
  "legacyHash": "59_6oxsvOzGf7Pjo6jPPn"
}
```
:::

:::hint{type="info"}
Retain the **segment** value for this user for use in subsequent API calls to Klevu.
:::

:::hint{type="info"}
IMPORTANT:  The segments may be updated for any given visitor throughout the session. To keep the segments relevant, please request an updated segment list after the **ttl** has expired.&#x20;
:::



# 2. Apply the Segments to the Recommendations Configuration

:::hint{type="success"}
Please review the section on API [Configurations](docId\:gp_Pf1_nMovk01Kou09nd) for a complete list of applicable parameters to use based on the application/placement of the Recommendation banner.
:::

:::ApiMethodV2
```json
{
  "name": "Use Segments",
  "method": "GET",
  "url": "https://config-cdn.ksearchnet.com/recommendations/<KLEVU_API_KEY>/settings/<KLEVU_RECS_KEY>",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "MSCNaYYDTcNS-YXQIV_dl",
        "language": "none",
        "code": "?sids=<SEGMENT_ID_A>,<SEGMENT_ID_B>,<SEGMENT_ID_C>\n",
        "customLabel": "Query Paramters"
      }
    ],
    "selectedLanguageId": "MSCNaYYDTcNS-YXQIV_dl"
  },
  "results": {
    "languages": [
      {
        "id": "jQ1mDftyBZv46iKCVqwE2",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"metadata\": {\n        \"title\": \"Still Looking For These?\",\n        \"recsKey\": \"<KLEVU_RECS_KEY>\",\n        \"pageType\": \"HOME\",\n        \"logic\": \"RECENTLY_VIEWED\",\n        \"maxProducts\": 10,\n        \"productThreshold\": 1,\n        \"enabled\": true,\n        \"spotKey\": \"<KLEVU_SPOT_KEY>\",\n        \"spotName\": \"Home Spot 1\",\n        \"segmentKey\": <SEGMENT_ID_A>,\n        \"segmentName\": \"Just Browsing\"\n    },\n    \"search\": {\n        \"basePath\": \"<KLEVU_SEARCH_DOMAIN>.ksearchnet.com/cs/v2/search\",\n        \"payload\": \"{\\\"recordQueries\\\":[{\\\"id\\\":\\\"klevuRECSItemList\\\",\\\"typeOfRequest\\\":\\\"SEARCH\\\",\\\"settings\\\":{\\\"typeOfRecords\\\":[\\\"KLEVU_PRODUCT\\\"],\\\"limit\\\":10}}]}\"\n    },\n    \"templates\": {\n        \"base\":  <KLEVU_RECS_MARKUP>\n    },\n    \"styles\": {\n        \"base\": <KLEVU_RECS_CSS>  \n    },\n    \"scripts\": {\n        \"recsObject\": <KLEVU_RECS_SCRIPTS>\n     }\n}"
      }
    ],
    "selectedLanguageId": "jQ1mDftyBZv46iKCVqwE2"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "name": "sids",
        "kind": "required",
        "type": "string",
        "description": "The SegmentIDs returned  as segmentInfo.segments within the previous request\n\n<SEGMENT_ID_A>,<SEGMENT_ID_B>,<SEGMENT_ID_C>",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "use-segments",
  "legacyHash": "WEnbiGZowpd4gd4kFRA6o"
}
```
:::

:::hint{type="info"}
Retain **spotKey**, **spotName**, **segmentKey**, **segmentName** for reference in the following Analytics collection API calls to Klevu.


The resulting **search.payload** JSON object will be the query payload used to call Klevu for the recommendations corresponding result set.
:::

#

# 3. Request and Display the Klevu Recommendations banner

Use the provided query structure from the **search.payload** json within the above response to retrieve the Recommendations array from Klevu


See the [Klevu Smart Recommendations API Overview](https://docs.klevu.com/apis/smart-recommendations-overview) for details on query specifics.

#

# 4. Collect Klevu Analytics

After the Recommendations have been displayed, collect the analytics to send to Klevu.

:::hint{type="info"}
Please use the appropriate **event** value for each **event** type

- Product recommendation impression: event = **view\_recs\_list&#x20;**
- Product clicks from recommendation banner: event = **select\_recs\_list**&#x20;
:::

:::ApiMethodV2
```json
{
  "name": "Recommendation Impression ",
  "method": "POST",
  "url": "https://stats.ksearchnet.com/analytics/collect",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "7KHvYGkpZG3Y-ht-CcQkU",
        "language": "json",
        "code": "[\n\t{\n\t\t\"event\": \"view_recs_list\",\n\t\t\"event_apikey\": \"<KLEVU_RECS_KEY>\",\n\t\t\"user_profile\": {\n\t\t\t\"session_id\": \"<KLEVU_SESSION_ID>\"\n\t\t},\n\t\t\"event_data\": {\n\t\t\t\"tags\": [\n\t\t\t\t\"recsPageType:HOME\"\n\t\t\t],\n\t\t\t\"list_id\": \"<KLEVU_RECS_KEY>\",\n\t\t\t\"list_name\": \"Still Looking For These?\",\n\t\t\t\"list_logic\": \"RECENTLY_VIEWED\",\n\t\t\t\"spot_id\": \"<KLEVU_RECS_KEY>\",\n\t\t\t\"spot_name\": \"Home Spot 1\",\n\t\t\t\"segment_id\": <SEGMENT_ID_A>,\n\t\t\t\"segment_name\": \"Just Browsing\",\n\t\t\t\"items\": [\n\t\t\t\t{\n\t\t\t\t\t\"item_id\": \"39814\",\n\t\t\t\t\t\"item_name\": \"Lorem Ipsum\",\n\t\t\t\t\t\"price\": \"25.0\",\n\t\t\t\t\t\"currency\": \"USD\",\n\t\t\t\t\t\"item_brand\": \"47\",\n\t\t\t\t\t\"item_variant\": \"39814\",\n\t\t\t\t\t\"item_group_id\": \"67466\",\n\t\t\t\t\t\"index\": 1,\n\t\t\t\t\t\"quantity\": 1\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"item_id\": \"32697\",\n\t\t\t\t\t\"item_name\": \"Gypsum Dolet\",\n\t\t\t\t\t\"price\": \"37.0\",\n\t\t\t\t\t\"currency\": \"USD\",\n\t\t\t\t\t\"item_brand\": \"47\",\n\t\t\t\t\t\"item_variant\": \"32697\",\n\t\t\t\t\t\"item_group_id\": \"83119\",\n\t\t\t\t\t\"index\": 2,\n\t\t\t\t\t\"quantity\": 1\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"item_id\": \"36888\",\n\t\t\t\t\t\"item_name\": \"Dolet Ipsum\",\n\t\t\t\t\t\"price\": \"26.0\",\n\t\t\t\t\t\"currency\": \"USD\",\n\t\t\t\t\t\"item_brand\": \"47\",\n\t\t\t\t\t\"item_variant\": \"36888\",\n\t\t\t\t\t\"item_group_id\": \"69215\",\n\t\t\t\t\t\"index\": 3,\n\t\t\t\t\t\"quantity\": 1\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t}\n]",
        "customLabel": "Request Body"
      }
    ],
    "selectedLanguageId": "7KHvYGkpZG3Y-ht-CcQkU"
  },
  "results": {
    "languages": [
      {
        "id": "WbdkYaM9kWR_k256DR3i4",
        "language": "200",
        "customLabel": "",
        "code": "200 HTTP response code"
      }
    ],
    "selectedLanguageId": "WbdkYaM9kWR_k256DR3i4"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "recommendation-impression",
  "legacyHash": "0NqYT6QSLmsFyJBiy2YiE"
}
```
:::

****

:::ApiMethodV2
```json
{
  "name": "Recommendation Product Click ",
  "method": "POST",
  "url": "https://stats.ksearchnet.com/analytics/collect",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "msv3rtWxyFzZVyTtoUBXr",
        "language": "json",
        "code": "[\n\t{\n\t\t\"event\": \"select_recs_list\",\n\t\t\"event_apikey\": \"<KLEVU_RECS_KEY>\",\n\t\t\"user_profile\": {\n\t\t\t\"session_id\": \"<KLEVU_SESSION_ID>\"\n\t\t},\n\t\t\"event_data\": {\n\t\t\t\"tags\": [\n\t\t\t\t\"recsPageType:HOME\"\n\t\t\t],\n\t\t\t\"list_id\": \"<KLEVU_RECS_KEY>\",\n\t\t\t\"list_name\": \"Still Looking For These?\",\n\t\t\t\"list_logic\": \"RECENTLY_VIEWED\",\n\t\t\t\"spot_id\": \"<KLEVU_RECS_KEY>\",\n\t\t\t\"spot_name\": \"Home Spot 1\",\n\t\t\t\"segment_id\": <SEGMENT_ID_A>,\n\t\t\t\"segment_name\": \"Just Browsing\",\n\t\t\t\"items\": [\n\t\t\t\t{\n\t\t\t\t\t\"item_id\": \"39814\",\n\t\t\t\t\t\"item_name\": \"Lorem Ipsum\",\n\t\t\t\t\t\"price\": \"25.0\",\n\t\t\t\t\t\"currency\": \"USD\",\n\t\t\t\t\t\"item_brand\": \"47\",\n\t\t\t\t\t\"item_variant\": \"39814\",\n\t\t\t\t\t\"item_group_id\": \"67466\",\n\t\t\t\t\t\"index\": 1,\n\t\t\t\t\t\"quantity\": 1\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t}\n]",
        "customLabel": "Request Body"
      }
    ],
    "selectedLanguageId": "msv3rtWxyFzZVyTtoUBXr"
  },
  "results": {
    "languages": [
      {
        "id": "2hhH3cihiOYJ7hOJKbV7d",
        "language": "200",
        "customLabel": "",
        "code": "200 HTTP response code"
      }
    ],
    "selectedLanguageId": "2hhH3cihiOYJ7hOJKbV7d"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "recommendation-product-click",
  "legacyHash": "5c3dC2kDN2Rg_OB5EfBzA"
}
```
:::


[title] Hand Picked
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any products which you, the merchant, has manually curated. The most common placements for this banner type are:

**Homepage: Our Recommended Products**
Show a recommendation banner with products you would like all customers to see.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Hand Picked Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify SEARCH."
      },
      {
        "kind": "required",
        "name": "customANDQuery",
        "type": "String",
        "description": "Here we make a custom query to Klevu, since we know exactly which records we expect in the response. Specify the IDs of all of the products you would like your customers to see, separated by OR"
      },
      {
        "kind": "required",
        "name": "topIds",
        "type": "Array",
        "description": "Use this field to specify the order the results should be returned, with the ones you would like to be more prominent coming first."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 7,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsHandPicked\",\n            \"meta\": {\n                \"qTime\": 4,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 2,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"color\": \"White Hoodie thick\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753152131\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"56.68\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=34322452512899,34322452971651,34322453430403,34322471256195,34322471551107,34322471846019,34322472173699\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322453430403\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797422_medium.jpg?v=1611184206&vid=34322466177155,34322466603139,34322466930819,34322467192963,34322467586179,34322467946627,34322468339843\",\n                    \"sku\": \"30504298-white-hoodie-thick-asian-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"48.48\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=34322452512899,34322452971651,34322453430403,34322471256195,34322471551107,34322471846019,34322472173699\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"56.68\",\n                    \"swatchesInfo\": \"variantColor1:Black Hoodie thin ;;;; variantColor3:Blue Hoodie thick ;;;; variantColor2:White Hoodie thick ;;;; variantColor5:White Hoodie thin ;;;; variantColor4:Black Hoodie thick ;;;; variantColor6:Yellow Hoodie thin ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=16847225487491 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797419_medium.jpg?v=1611184206&vid=16847185313923 ;;;; variantId6:34322463555715 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=16847185510531 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=16847190851715 ;;;; variantId4:34322456838275 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797418_medium.jpg?v=1611184250&vid=16847223521411 ;;;; variantId5:34322460016771 ;;;; variantId2:34322452512899 ;;;; variantId3:34322453889155 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797425_medium.jpg?v=1611184240&vid=16847221883011 ;;;; variantId1:34322448646275 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-hoodies-men-women-2021-spring-sweatshirt-male-japanese-streetwear-oversized-yellow-anime-hoodie-men-sweatshirts\",\n                    \"size\": \"Asian-M\",\n                    \"name\": \"Singleroad Men's Hoodies Men Women 2021 Sweatshirt Male Japanese Streetwear Oversized Anime Hoodie Men Sweatshirts\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192749842563\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322423840899\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882422-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-printed-hooded-oversize-knitted-sweatshirt\",\n                    \"name\": \"WoMen's Printed Hooded Oversize Knitted Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsHandPicked\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\":\"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsHandPicked\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\":\"(id:\\\\\"34322453430403\\\\\" OR id:\\\\\"34322423840899\\\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "// WARNING: For POST requests, body is set to null by browsers.\nvar data = JSON.stringify({\n  \"recordQueries\": [\n    {\n      \"id\": \"recsHandPicked\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\": \"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = true;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\r\\n  \\\"recordQueries\\\": [\\r\\n    {\\r\\n      \\\"id\\\": \\\"recsHandPicked\\\",\\r\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\r\\n      \\\"settings\\\": {\\r\\n        \\\"customANDQuery\\\":\\\"(id:\\\\\\\"34322453430403\\\\\\\" OR id:\\\\\\\"34322423840899\\\\\\\")\\\",\\r\\n        \\\"topIds\\\": [\\r\\n          {\\r\\n            \\\"key\\\": \\\"id\\\",\\r\\n            \\\"value\\\": \\\"34322453430403\\\"\\r\\n          },\\r\\n          {\\r\\n            \\\"key\\\": \\\"id\\\",\\r\\n            \\\"value\\\": \\\"34322423840899\\\"\\r\\n          }\\r\\n        ],\\r\\n        \\\"typeOfRecords\\\": [\\r\\n          \\\"KLEVU_PRODUCT\\\"\\r\\n        ]\\r\\n      }\\r\\n    }\\r\\n  ],\\r\\n  \\\"context\\\": {\\r\\n    \\\"apiKeys\\\": [\\r\\n      \\\"klevu-158755634955912036\\\"\\r\\n    ]\\r\\n  }\\r\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    \"recordQueries\": [\n      {\n        \"id\": \"recsHandPicked\",\n        \"typeOfRequest\": \"SEARCH\",\n        \"settings\": {\n          \"customANDQuery\": \"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n          \"topIds\": [\n            {\n              \"key\": \"id\",\n              \"value\": \"34322453430403\"\n            },\n            {\n              \"key\": \"id\",\n              \"value\": \"34322423840899\"\n            }\n          ],\n          \"typeOfRecords\": [\n            \"KLEVU_PRODUCT\"\n          ]\n        }\n      }\n    ],\n    \"context\": {\n      \"apiKeys\": [\n        \"klevu-158755634955912036\"\n      ]\n    }\n  })\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "jSU7DlYyJ_eUh63YSP682"
  },
  "description": "The end-point is used for retrieving hand picked product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "hand-picked-product-recommendations",
  "legacyHash": "AehSnlU30i4_pCisP-Q9j"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=handPicked&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Advanced Filtering
[path] Guide/Smart Search/

In the "faceting" section, we highlight how one can obtain available filters for a search query and apply filters to narrow down search results. For example, after searching for "shoes", a shopper may want to narrow down results by applying a filter on the color attribute and choosing a value such as red. Doing so will show only "red" shoes in the results. If at this point, the shopper chooses yet another color, e.g., blue, Klevu will now show both the "red" and the "blue" shoes. Thus, it will apply the OR operation between the values of the same attribute. If at this stage, the shopper chooses "cotton" as a material, the system will show both the red and blue shoes, but it will also ensure all products have "cotton" as a material as well. In other words, it applies the AND operation among the different types of selected attributes.

However, there comes a time when one may want to perform complex filtering operations, or in other words, advanced filtering operations. For example, you may want to show a group of shoes where the "color is red", and the "brand is NOT Adidas". You may also want to add another group of shoes to this result set. For example, where the "color is blue or black", "brand is Nike", and the "price range is between 100 and 400". As you can see, unlike the behaviour of "faceting", in our example here, we like to have one or more groups of products matching different groups of conditions for the final set of products to be returned.

It is with this intention to allow advanced filtering operations on the result set that we have introduced a new functionality called "advanced filtering" in our API.

Before the introduction of advanced filtering, if a user had requested filters to be returned or some to be applied, Klevu used to find out a set of relevant products matching the user query. It then included/excluded any products requested explicitly in this result set. It is after this stage that it calculates all possible filters to be returned and also applies the selected filters to narrow down the search results. Thus, if an explicitly added product did not match the applied filter, it would be excluded from the final result set.

With the addition of advanced filtering, Klevu now identifies a set of relevant products matching the query. It then applies advanced filtering to this. It is after this step that it includes/excludes any products requested explicitly, calculates filters based on this result set, and finally applies the selected filters to narrow down the search results. This way, if there is any filtering to be applied prior to including/excluding products explicitly, advanced filtering should be used.

:::hint{type="info"}
Please note that the advanced filtering can also be used with Category Merchandising and Recommendation APIs.
:::

The **groupCondition&#x20;**&#x6F;bject can be used for applying the advanced filtering conditions so your customers can fine-tune their results based on relevant attributes.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Apply Advanced Filtering",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "groupOperator",
        "type": "string",
        "description": "Defining the condition of filtering. Here are the options available.\nALL_OF:This is used to filter data using AND query i.e. the search results are matching with all the attributes.\n\nANY_OF:This is used to filter data using OR query i.e. the search results are matching with at least one attributes.\n\nNONE_OF: This is used as negation AND query i.e.  when search results are matching with none of the attribute values."
      },
      {
        "kind": "optional",
        "name": "key",
        "type": "string",
        "children": [],
        "description": "The ID of the attribute to filter by, eg. color"
      },
      {
        "kind": "optional",
        "name": "valueOperator",
        "type": "string",
        "children": [],
        "description": "\t\nDefining an attribute's operation, Here are the options available.\n\nINCLUDE : This is used to include specific attribute for the filter purpose.\n\nEXCLUDE :  This is used to exclude specific attribute for the filter purpose.\n\nEXISTS: This is used to find if the specific indexed attribute value exists with product.\n\n NOT_EXISTS : This is used to find if the specific indexed attribute value does not exist at all."
      },
      {
        "kind": "optional",
        "name": "singleSelect",
        "type": "Boolean",
        "children": [],
        "description": "The behaviour when specifying multiple filters or values.\n\nIf it is set to \"true\", the products returned must have both the values.\nIf it is set to \"false\", the products returned must have at least one of the values.\n"
      },
      {
        "kind": "optional",
        "name": "excludeValuesInResult",
        "type": "Boolean",
        "children": [],
        "description": "For numeric filter like price, can be used to exclude data of the starting or ending values. For example if the range is defined as \"1200 - 1232\" in values, and excludeValuesInResult is set to true, Klevu will use range as “1201 - 1231“.\n\nThis can be used to achieve greater than or less than condition. For example,if  you want to get the products greater than price 200, the values field will be “200 - *“ and the excludeValuesInResult will be set to true."
      },
      {
        "kind": "optional",
        "name": "values",
        "type": "Array",
        "children": [],
        "description": "An array of values to filter by, eg. Red, Blue. When using range filters, specify the first value as the minimum value and the second as the max value. For example to retrieve records with prices between 60 to 80, use: \"key\": \"klevu_price\", \"values\": [60, 80]. \nTo retrieve steps of prices, for example those with values between 0-50 or 150-200, use: \"key\": \"klevu_price\", \"values\": [\"0-50\", \"150-200\"]. \n\nTo retrieve exact values, for example records with exact values 100 or 200, use: \"key\": \"klevu_price\", \"values\": [\"100-100\", \"200-200\"]. \nBy default all attributes submitted to Klevu are indexed as STRING attributes, which means they cannot be used as range filters. The product sale price field is the only exception to this rule, which is filtered using the key klevu_price. If you have explicitly requested and Klevu has approved that certain attributes be indexed as numerical attributes, you can also retrieve those as range filters."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "r-TJAKr3_5xMIwv1KRrWj",
        "code": "{\n    \"meta\": {\n        \"qTime\": 9,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 7,\n                \"noOfResults\": 2,\n                \"totalResultsFound\": 6,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"tee\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Tees\",\n                    \"itemGroupId\": \"4384027344958\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"24.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ws05-yellow_main_fe09e105-6b7e-4269-9b53-edc3735127ba_medium.jpg?v=1575477895\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366447038526\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WS05-XS-Yellow\",\n                    \"brand\": \"KKE\",\n                    \"basePrice\": \"24.0\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ws05-yellow_main_fe09e105-6b7e-4269-9b53-edc3735127ba_medium.jpg?v=1575477895\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"24.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Tees  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/desiree-fitness-tee-yellow\",\n                    \"tags\": \"comfort, flattering fit, micro-sleeve, summer, v-neck\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Desiree Fitness Tee\",\n                    \"shortDesc\": \"When you're too far to turn back, thank yourself for choosing the Desiree Fitness Tee. Its ultra-lightweight, ultra-breathable fabric wicks sweat away from your body and helps keeps you cool for the distance. • Short-Sleeves. • Performan\",\n                    \"category\": \"Tees\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Tees\",\n                    \"itemGroupId\": \"4384047759422\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"24.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ms01-yellow_main_11be227e-034a-4bb1-ae91-ef28227d26ed_medium.jpg?v=1575478213\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366478200894\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MS01-XS-Yellow\",\n                    \"brand\": \"MNH\",\n                    \"basePrice\": \"24.0\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ms01-yellow_main_11be227e-034a-4bb1-ae91-ef28227d26ed_medium.jpg?v=1575478213\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"24.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Tees  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/aero-daily-fitness-tee-yellow\",\n                    \"tags\": \"Comfort, crew-neck, machine, relaxed-fit, short-sleev, Yellow\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Aero Daily Fitness Tee\",\n                    \"shortDesc\": \"Need an everyday action tee that helps keep you dry? The Aero Daily Fitness Tee is made of 100% polyester wicking knit that funnels moisture away from your skin. Don't be fooled by its classic style; this tee hides premium performance technology b\",\n                    \"category\": \"Tees\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "r-TJAKr3_5xMIwv1KRrWj"
  },
  "examples": {
    "languages": [
      {
        "id": "ckgzYslV7r8QJUVAtHyzF",
        "language": "javascript",
        "code": "{\n   \"context\":{\n      \"apiKeys\":[\n         \"klevu-156925593843210765\"\n      ]\n   },\n   \"recordQueries\":[\n      {\n         \"id\":\"productSearch\",\n         \"typeOfRequest\":\"SEARCH\",\n         \"settings\":{\n            \"typeOfRecords\":[\n               \"KLEVU_PRODUCT\"\n            ],\n            \"groupCondition\":{\n               \"groupOperator\":\"ANY_OF\",\n               \"conditions\":[\n                  {\n                     \"key\":\"klevu_price\",\n                     \"valueOperator\":\"INCLUDE\",\n                     \"singleSelect\":true,\n                     \"excludeValuesInResult\":true,\n                     \"values\":[\n                        \"20 - 25\"\n                     ]\n                  },\n                  {\n                     \"key\":\"itemGroupId\",\n                     \"valueOperator\":\"EXCLUDE\",\n                     \"singleSelect\":false,\n                     \"values\":[\n                        \"4384028262462\"\n                     ]\n                  },\n                  {\n                     \"key\":\"size\",\n                     \"valueOperator\":\"EXCLUDE\",\n                     \"singleSelect\":false,\n                     \"values\":[\n                        \"Small\",\n                        \"Large\"\n                     ]\n                  },\n                  {\n                     \"key\":\"brand\",\n                     \"valueOperator\":\"EXISTS\"\n                  },\n                  {\n                     \"key\":\"discount\",\n                     \"valueOperator\":\"NOT_EXISTS\"\n                  }\n               ]\n            },\n            \"query\":{\n               \"term\":\"tee\"\n            },\n            \"limit\":2\n         }\n      }\n   ]\n}",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "KzctSNC3rkjgpRBccF8m9",
        "language": "php",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n    \"context\": {\n        \"apiKeys\": [\n            \"klevu-156925593843210765\"\n        ]\n    },\n    \"recordQueries\": [\n        {\n            \"id\": \"productSearch\",\n            \"typeOfRequest\": \"SEARCH\",\n            \"settings\": {\n                \"typeOfRecords\": [\n                    \"KLEVU_PRODUCT\"\n                ],\n                \"groupCondition\": {\n                    \"groupOperator\": \"ANY_OF\",\n                    \"conditions\": [\n                        {\n                            \"key\":\"klevu_price\",\n                            \"valueOperator\":\"INCLUDE\",\n                            \"singleSelect\":true,\n                            \"excludeValuesInResult\":true,\n                            \"values\":[\n                                \"20 - 25\"\n                            ]\n                        },\n                        {\n                            \"key\": \"itemGroupId\",\n                            \"valueOperator\": \"EXCLUDE\",\n                            \"singleSelect\": false, \n                            \"values\": [\n                                \"4384028262462\"\n                            ]\n                        },\n\t\t\t\t\t\t{\n\t\t\t\t\t\t \"key\":\"size\",\n\t\t\t\t\t\t \"valueOperator\":\"EXCLUDE\",\n\t\t\t\t\t\t \"singleSelect\":false,\n\t\t\t\t\t\t \"values\":[\n\t\t\t\t\t\t\t\"Small\",\n                            \"Large\"\n\t\t\t\t\t\t ]\n\t\t\t\t\t  },\n                      {\n\"key\": \"brand\",\n\"valueOperator\": \"EXISTS\"\n},\n{\n\"key\": \"discount\",\n\"valueOperator\": \"NOT_EXISTS\"\n}\n                    ]\n                },\n                \"query\": {\n                    \"term\": \"tee\"\n                },\n                \"limit\": 2\n            }\n        }\n    ]\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "customLabel": ""
      },
      {
        "id": "0Km4dtw6lHpnb6PVYe38Z",
        "language": "javascript",
        "code": "// WARNING: For POST requests, body is set to null by browsers.\nvar data = JSON.stringify({\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  },\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"groupCondition\": {\n          \"groupOperator\": \"ANY_OF\",\n          \"conditions\": [\n            {\n              \"key\": \"klevu_price\",\n              \"valueOperator\": \"INCLUDE\",\n              \"singleSelect\": true,\n              \"excludeValuesInResult\": true,\n              \"values\": [\n                \"20 - 25\"\n              ]\n            },\n            {\n              \"key\": \"itemGroupId\",\n              \"valueOperator\": \"EXCLUDE\",\n              \"singleSelect\": false,\n              \"values\": [\n                \"4384028262462\"\n              ]\n            },\n            {\n              \"key\": \"size\",\n              \"valueOperator\": \"EXCLUDE\",\n              \"singleSelect\": false,\n              \"values\": [\n                \"Small\",\n                \"Large\"\n              ]\n            },\n            {\n              \"key\": \"brand\",\n              \"valueOperator\": \"EXISTS\"\n            },\n            {\n              \"key\": \"discount\",\n              \"valueOperator\": \"NOT_EXISTS\"\n            }\n          ]\n        },\n        \"query\": {\n          \"term\": \"tee\"\n        },\n        \"limit\": 2\n      }\n    }\n  ]\n});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = true;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "customLabel": ""
      },
      {
        "id": "KzIQNEra_BMHMph_5WFvo",
        "language": "java",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\r\\n    \\\"context\\\": {\\r\\n        \\\"apiKeys\\\": [\\r\\n            \\\"klevu-156925593843210765\\\"\\r\\n        ]\\r\\n    },\\r\\n    \\\"recordQueries\\\": [\\r\\n        {\\r\\n            \\\"id\\\": \\\"productSearch\\\",\\r\\n            \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\r\\n            \\\"settings\\\": {\\r\\n                \\\"typeOfRecords\\\": [\\r\\n                    \\\"KLEVU_PRODUCT\\\"\\r\\n                ],\\r\\n                \\\"groupCondition\\\": {\\r\\n                    \\\"groupOperator\\\": \\\"ANY_OF\\\",\\r\\n                    \\\"conditions\\\": [\\r\\n                        {\\r\\n                            \\\"key\\\":\\\"klevu_price\\\",\\r\\n                            \\\"valueOperator\\\":\\\"INCLUDE\\\",\\r\\n                            \\\"singleSelect\\\":true,\\r\\n                            \\\"excludeValuesInResult\\\":true,\\r\\n                            \\\"values\\\":[\\r\\n                                \\\"20 - 25\\\"\\r\\n                            ]\\r\\n                        },\\r\\n                        {\\r\\n                            \\\"key\\\": \\\"itemGroupId\\\",\\r\\n                            \\\"valueOperator\\\": \\\"EXCLUDE\\\",\\r\\n                            \\\"singleSelect\\\": false, \\r\\n                            \\\"values\\\": [\\r\\n                                \\\"4384028262462\\\"\\r\\n                            ]\\r\\n                        },\\r\\n\\t\\t\\t\\t\\t\\t{\\r\\n\\t\\t\\t\\t\\t\\t \\\"key\\\":\\\"size\\\",\\r\\n\\t\\t\\t\\t\\t\\t \\\"valueOperator\\\":\\\"EXCLUDE\\\",\\r\\n\\t\\t\\t\\t\\t\\t \\\"singleSelect\\\":false,\\r\\n\\t\\t\\t\\t\\t\\t \\\"values\\\":[\\r\\n\\t\\t\\t\\t\\t\\t\\t\\\"Small\\\",\\r\\n                            \\\"Large\\\"\\r\\n\\t\\t\\t\\t\\t\\t ]\\r\\n\\t\\t\\t\\t\\t  },\\r\\n                      {\\r\\n\\\"key\\\": \\\"brand\\\",\\r\\n\\\"valueOperator\\\": \\\"EXISTS\\\"\\r\\n},\\r\\n{\\r\\n\\\"key\\\": \\\"discount\\\",\\r\\n\\\"valueOperator\\\": \\\"NOT_EXISTS\\\"\\r\\n}\\r\\n                    ]\\r\\n                },\\r\\n                \\\"query\\\": {\\r\\n                    \\\"term\\\": \\\"tee\\\"\\r\\n                },\\r\\n                \\\"limit\\\": 2\\r\\n            }\\r\\n        }\\r\\n    ]\\r\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "customLabel": ""
      },
      {
        "id": "zhIqFphBHfQcSzStcYLq_",
        "language": "nodejs",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    \"context\": {\n      \"apiKeys\": [\n        \"klevu-156925593843210765\"\n      ]\n    },\n    \"recordQueries\": [\n      {\n        \"id\": \"productSearch\",\n        \"typeOfRequest\": \"SEARCH\",\n        \"settings\": {\n          \"typeOfRecords\": [\n            \"KLEVU_PRODUCT\"\n          ],\n          \"groupCondition\": {\n            \"groupOperator\": \"ANY_OF\",\n            \"conditions\": [\n              {\n                \"key\": \"klevu_price\",\n                \"valueOperator\": \"INCLUDE\",\n                \"singleSelect\": true,\n                \"excludeValuesInResult\": true,\n                \"values\": [\n                  \"20 - 25\"\n                ]\n              },\n              {\n                \"key\": \"itemGroupId\",\n                \"valueOperator\": \"EXCLUDE\",\n                \"singleSelect\": false,\n                \"values\": [\n                  \"4384028262462\"\n                ]\n              },\n              {\n                \"key\": \"size\",\n                \"valueOperator\": \"EXCLUDE\",\n                \"singleSelect\": false,\n                \"values\": [\n                  \"Small\",\n                  \"Large\"\n                ]\n              },\n              {\n                \"key\": \"brand\",\n                \"valueOperator\": \"EXISTS\"\n              },\n              {\n                \"key\": \"discount\",\n                \"valueOperator\": \"NOT_EXISTS\"\n              }\n            ]\n          },\n          \"query\": {\n            \"term\": \"tee\"\n          },\n          \"limit\": 2\n        }\n      }\n    ]\n  })\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ckgzYslV7r8QJUVAtHyzF"
  },
  "description": "Example is as below:",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "apply-advanced-filtering",
  "legacyHash": "no8rdO8taBnY-d7Mgptw7"
}
```
:::

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=advanceFiltering&#x22;&#xD;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xD;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xD;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xD;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xD;&#xA;     &#xD;&#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Connectors
[path] Guide/


[title] Send a Message
[path] Guide/MOI/

# Sending a Message

In its simplest form, the backend expects a plain text message written in a natural language and when sending this message, it is important to add the `sessionId` and `klevuApiKey` in the **context**.

**Request:**

```json
{

  "context": {

    "sessionId": "e7e0b73b-e160-4585-98b8-f50cbfdfe9ba",

    "klevuApiKey": "<store's api key>"

  },

  "message": "do you have dresses?"

}
```



# Understanding the Response JSON

With every message sent to the backend, in its response, it will always return the context containing the respective `sessionId` and the `klevuApiKey`.  Additionally, it may come back with different types of data elements. It may look like the following with one or more elements of each type.

**Response:**

```json
{

  "data":[

    { "context": { …...} },

    { "message": { ... } },

    { "filter": { ... } },

    { "productData": { ... }},

    { "genericOptions": { ... }},

    { "actions": { ... }}

  ]

}
```

Lets have a look at each data type in the response :

## **context** 

```json
...
  
    "context": {

        "sessionId": "<some session id>",

        "klevuApiKey": "<store's api key>",
         
        "ipAddressV4":"XXX.XXX.XXX.XXX",
       
        "ipAddressV6":"X:X:X:X:X:X:X:X",
    
        "dataProtection":true/false,
    
        "country":"FR",
    
        "city":"Paris",
	
	    "klevu_uuid":"0ff61cc7-4a55-4b3a-b9f8-975ea2b248ea" 

    }
    
...
```

| **Parameter** | **Description**                                                                                              |
| ------------- | ------------------------------------------------------------------------------------------------------------ |
| sessionId     | The sessionId assigned to the current user and should be used for any subsequent interactions by this user.  |
| klevuApiKey   | The Klevu API key used for the session.                                                                      |

###

## **message**

```json
...

   "message": {

        "id": "6aed823a-1ecc-457a-8d60-d32972408d78",

        "type": "text",

        "value": "I am your shopping assistant. How can I help you?",

        "note": null,

        "explain": null,

        "collectFeedback": false

    }
...
```

| **Parameter**   | **Description**                                                                                                                                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id              | Every message is assigned a unique `id`.  This is used when submitting shopper’s feedback for this particular message. We will see an example of the same a bit later in the document.                            |
| type            | In the current version, the value of this remains as "text".                                                                                                                                                      |
| value           | The message you want to show to the shopper.  The value here is usually a plain text but can also contain URLs and therefore the respective html anchors in it.                                                   |
| note            | This is like a fine print or an instruction or a general note that you may want to show as a fine print to the current message.                                                                                   |
| explain         | Why the system has produced the answer it has, the explanation of the same is provided in this element. It details the reasoning the backend system has followed. In our UIs we show them behind the *info* icon. |
| collectFeedback | If set to `true`, this is an instruction to the frontend that feedback should be collected for this particular message.                                                                                           |

:::hint{type="warning"}
There can be one or more of this in a single request. When rendering messages on the front, please show them in the order they are provided in the response.&#x20;
:::



## filter 

These are different filtering options the MOI backend likes to present to the shopper and ask to choose from.  For example, if a shopper has asked for dresses, the MOI application may want to show some colors or sizes or other attributes to collect shopper’s preferences.

![](https://lh7-us.googleusercontent.com/vStfrf88bbpc5ViiIuuAMQFIbib68VR_4EJOLu3fVjV4K8QGxMrj4zfszqBUnKxq2c6NJmOxDZUIROJ4t5rBDsdijFmh3bLzNS0gqxuQ370ezBT2ytW6ClomuR-lnZBA1uxR6lmABMJZTp1wUTtfVY0)

```json
...

   "filter": {
       "settings": {
         "label": "Please select a size:",
         "key": "size",
         "chatFormat": "$VALUE$ please!",
         "chatFormatEmpty": "Any Size would do!"
       },
       "options": [{
           "name": "s",
           "value": "size:s",
           "selected": "false",
           "count": "31"
         },
         {
           "name": "m",
           "value": "size:m",
           "selected": "false",
           "count": "30"
         },
         
         ...
         
       ],
       "note": null
     }
...
```

### **filter.settings**

| **Parameter**   | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| label           | Shows a message to be shown to the shopper before listing down the options.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| key             |  The id/key of the filter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| chatFormat      | When a shopper has selected an option, there are two things we like to do.<br />1) Show in the chat message the option that the shopper has selected.
2) Send a filter selection to the MOI backend.<br />The `chatFormat` here shows the template that can be used to prepare a message that should be shown to the shopper. <br />Here, for example, the chat format is "$VALUE$ please!".  <br />The $VALUE$ should be replaced with the actual option (or options) selected. For example "small and medium please!".<br />&#xA; |
| chatFormatEmpty |  This is for future reference and can be ignored for now.                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |



### filter.options

| **Parameter** | **Description**                                                                                                                       |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| name          | Caption of the option (e.g. "s", "m").                                                                                                |
| value         | If a customer chooses this option, the value to be sent to the backend. We will see later in the documentation how to use this value. |
| selected      |  If this option was already selected by the shopper. It comes as true or false/null.                                                  |
| count         | The number of products MOI has for this option.                                                                                       |



## productdata

This is where the actual products to be shown to the shopper are sent from the MOI backend. For each product it shows some product specific options as well.

![](https://lh7-us.googleusercontent.com/N2dfRpqg5Tjfz0ne-Pu9aaj008vCxkhUhsn4XajGJ1wM_lH61yGvD9j8ZlEH9vNU6Lvzs136pIoph0H1W-7HoI5QYsvtZA7pYFeOa-qqQnJYf5Y62cCQLHWZ53AACANmYdUxAedG-NUICZbSRgOr5Eg)



```json
...

{
  "productData": {
    "products": [{
      "id": "40991197921373",
      "itemRef": "P0",
      "itemGroupId": "7081251209309",
      "image": "<url of the image>",
      "name": "<product title>",
      "url": "<product url>",
      "price": "98.00",
      "salePrice": "90.00",
      "currency": "USD",
      "shortDesc": "<short description of the product>",
      "originalContent": "<long description of the product>",
      "noOfVariants": 0,
      "options": [{
          "name": "Product Questions",
          "intent": "product-specific-question",
          "chat": "Product Questions"
        },
        {
          "name": "More Like This",
          "intent": "show-similar-products",
          "chat": "Similar Products to P0"
        }
      ]
    },
    ...
    ],
    "totalResultsFound": "15",
    "typeOfQuery": "wildcard_and",
    "note": "Tip: you can ask questions using product locators, e.g. what’s the difference between p0 and p1?"
  }
}

...

```

| **Parameter**     | **Description**                                                                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------- |
| products          | The array of individual data points for each of the product records (see `productData.products` section below). |
| totalResultsFound | the total number of results found.                                                                              |
| typeOfQuery       | You may ignore this as this is only used for debugging.                                                         |
| note              | A fine print that you may want to show to the shopper.                                                          |



### productData.products

| **Parameter**   | **Description**                                                                                                                                                                                                         |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id              | The unique id of the product.                                                                                                                                                                                           |
| itemRef         | This is a product locator (e.g. p0 and p1). Shoppers can include these references in their question.                                                                                                                    |
| itemGroupId     | The parent group id of the product. In case of a product having multiple variants, a group id is associated with every variant.                                                                                         |
| image           | The URL of the image to be used to fetch product image.                                                                                                                                                                 |
| name            | The title of the product.                                                                                                                                                                                               |
| url             | URL of the product.                                                                                                                                                                                                     |
| price           | Retail price of the product.                                                                                                                                                                                            |
| salePrice       | Price after discount.                                                                                                                                                                                                   |
| currency        | 3 letter currency code.                                                                                                                                                                                                 |
| shortDesc       | Short description of the product.                                                                                                                                                                                       |
| originalContent | Long description of the product.                                                                                                                                                                                        |
| noOfVariants    | If there are other variants of this product available. This field contains the count of these variants.                                                                                                                 |
| **options**     | **The options to be shown in the UI for this product.&#x20;**&#xA;**For each option, it contains the following sub elements:**                                                                                          |
| options.name    | Caption for the option.                                                                                                                                                                                                 |
| options.intent  | When a shopper clicks on this option and when you send a call to answer this click, it will require you to submit the intent. How exactly such a product specific option be handled is explained later in the document. |
| options.chat    | The message to be posted in the chat window when handling this option.                                                                                                                                                  |



## genericOptions

These are different dynamic options that are relevant in the current state after the last response was sent. In our UIs, we convert them into buttons.&#x20;

![](https://lh7-us.googleusercontent.com/c5NAeukuyXN9qwaNasXAGM3LRIcqySdL2QHbVg-kFcgj3PUcO3qilTHivARIjT_guhK_XEU_VIrXmZjVRxeJVzmi7JPenha3zLoLzwR9OwDhEUxEAf45pFrQoYQBCAnWb21ZDELxlOQNuK6iRxo2Kqc)

```json
...
{
  "genericOptions": {
    "options": [{
        "name": "Back",
        "type": "message",
        "chat": "Go back"
      },
      {
        "name": "Clear",
        "type": "clearChat",
        "chat": null
      },
      
      ...
      
    ]  }}

...
```

| **Parameter** | **Description**                                                                                                                                                                                                                                                                                                                                     |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name          | This is like a caption of a button                                                                                                                                                                                                                                                                                                                  |
| type          | There are two types supported:<br />&#xA;`message`: if the type is “message”, when a shopper clicks on it, the associated chat should be posted in the chat window and sent as a message to the MOI backend.<br />&#xA;`clearChat`: if the type is “clearChat”, the chat UI should be cleared. No need to send any message to the MOI backend.&#xA; |
| chat          | When a shopper hits on the button for these options, the text provided here should be posted in the chat window and sent as a message to the MOI backend.                                                                                                                                                                                           |



## actions

The MOI backend may want you to take certain actions such as redirect shoppers to a particular page or collect their order number for order tracking etc. For such matters, it may include certain information in the response.

Here, for example, the action is to redirect the shopper to a particular URL.

```json
...
   {
      "actions": {
        "actions": [{
          "type": "redirectToUrl",
          "context": {
            "link": "<url of a page / product>"
          }
        }]
      }
    }
...
```

| **Parameter** | **Description**                             |
| ------------- | ------------------------------------------- |
| actions       | There maybe more than one action available. |
| type          | There action type.                          |
| context       | The action context.                         |








[title] Record search
[path] Guide/Smart Search/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

The recordQuery object is used for **searching for records**. Use this for retrieving Products, Categories, CMS Pages or your own Custom Entity types when your customer has submitted a search query.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Record search",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "id",
        "type": "string",
        "description": "Every suggestion request must have a unique identifier associated with it. When a result is retrieved, the ID of each query is associated with it's respective response."
      },
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "string",
        "description": "This parameter defines the type of request, which should be 'SEARCH' for standard search queries. There are other values available, detailed elsewhere in the documentation."
      },
      {
        "kind": "required",
        "name": "query",
        "type": "string",
        "description": "The search term or phrase for which the suggestions are retrieved from Klevu Search."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 7,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 6,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 104,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016334910\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431146046\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Green\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-green\",\n                    \"tags\": \"body-hugging, Green, nylon, Running, Short\",\n                    \"size\": \"Small\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016269374\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431080510\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Purple\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-purple\",\n                    \"tags\": \"body-hugging, nylon, Red, Running, Short\",\n                    \"size\": \"Large\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016203838\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431014974\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-red\",\n                    \"tags\": \"body-hugging, nylon, Red, Running, Short\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384040386622\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"32.50\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465781822\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH03-32-Black\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.5\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/meteor-workout-short-black\",\n                    \"tags\": \"black, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Small\",\n                    \"name\": \"Meteor Workout Short\",\n                    \"shortDesc\": \"Step into the Meteor Workout Short for an incredibly lightweight fitness experience. Its breathable construction and an inner brief provide additional comfort and support, while the adjustable waistband offers the perfect fit to take you to the fi\",\n                    \"category\": \"Shorts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384039665726\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"29.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465060926\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH05-32-Gray\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"29.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-gray\",\n                    \"tags\": \"Gray, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"shortDesc\": \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n                    \"category\": \"Shorts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: text/plain'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\";\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"text/plain\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"text/plain\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"text/plain\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'text/plain'\n  },\n  body: '{\\n  \"recordQueries\": [\\n    {\\n      \"id\": \"productSearch\",\\n      \"typeOfRequest\": \"SEARCH\",\\n      \"settings\": {\\n        \"query\": {\\n          \"term\": \"short\"\\n        },\\n        \"limit\": 5,\\n        \"typeOfRecords\": [\\n          \"KLEVU_PRODUCT\"\\n        ]\\n      }\\n    }\\n  ],\\n  \"context\": {\\n    \"apiKeys\": [\\n      \"klevu-156925593843210765\"\\n    ]\\n  }\\n}'\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "8Yg33Te4JzfoWp5yEbmJh"
  },
  "description": "This is an example to fetch instant auto complete using APIs.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "record-search",
  "legacyHash": "7jT18yWn9BVpwV5mTA8St"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=recordSearch&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Category Product Search
[path] Guide/Smart Category Merchandising/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Category search",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "This parameter defines the type of request it is, which should be 'CATNAV' for category merchandising queries. There are other values available, detailed elsewhere in the documentation."
      },
      {
        "kind": "required",
        "name": "categoryPath",
        "type": "String",
        "description": "Specify the name of the category to retrieve results from, in the same case and format as it is indexed with Klevu.\n\nFor nested categories, use the ; character to separate the hierarchy. For example, for 'Mens > Shoes > Trainers and Sneakers' you would specify: Mens;Shoes;Trainers and Sneakers."
      },
      {
        "name": "merchandisingVersion",
        "kind": "optional",
        "type": "integer",
        "description": "This is related to Klevu category Merchandising Webhook:\nhttps://help.klevu.com/support/solutions/articles/5000892289-klevu-webhook-integration-guide\nWhen a webhook for Category Merchandising is received, this field will be included in the request payload. Pass this field when some Merchandising rule is being updated and search-cache bypass is needed.",
        "": "This is related to Klevu category Merchandising Webhook:\nhttps://help.klevu.com/support/solutions/articles/5000892289-klevu-webhook-integration-guide\nWhen a webhook for Category Merchandising is received, this field will be included in the request payload. Pass this field when some Merchandising rule is being updated and search-cache bypass is needed."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 7,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"categoryProducts\",\n            \"meta\": {\n                \"qTime\": 5,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 73,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Hoodies & Sweatshirts\",\n                    \"itemGroupId\": \"4384033833022\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"75.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-red_main_c9193846-bc80-4537-b810-4f6ad82dd6fe_medium.jpg?v=1575478019\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456541246\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ01-S-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-red_main_c9193846-bc80-4537-b810-4f6ad82dd6fe_medium.jpg?v=1575478019\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"75.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets;;Hoodies & Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/stellar-solar-jacket-s-red\",\n                    \"tags\": \"Cold-whether, comfortable, crewneck, Grayson, Hoodie, machine, Sweatshirt, winter, Wool\",\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"shortDesc\": \"Beat the heat and protect yourself from sunrays with the Stellar Solar Jacket. It's loaded with all the engineered features you need for an intense, safe outdoor workout: 100% UV protection, a breathable perforated construction, and advanced moist\",\n                    \"category\": \"Jackets;;Hoodies & Sweatshirts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052215870\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-blue_main_bb248254-73cc-4521-8105-fe2277267348_medium.jpg?v=1575478286\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487441470\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Blue\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-blue_main_bb248254-73cc-4521-8105-fe2277267348_medium.jpg?v=1575478286\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-blue\",\n                    \"tags\": \"blue, machine, royal, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033341502\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-orange_main_098af8fb-1cf2-473f-907a-10922e39beae_medium.jpg?v=1575478007\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455590974\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-Orange\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-orange_main_098af8fb-1cf2-473f-907a-10922e39beae_medium.jpg?v=1575478007\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-orange\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384031244350\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"77.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj06-green_main_30b7fa7f-a3ce-4513-9307-822bf013a89d_medium.jpg?v=1575477963\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366453067838\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ06-XS-Green\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj06-green_main_30b7fa7f-a3ce-4513-9307-822bf013a89d_medium.jpg?v=1575477963\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"77.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/juno-jacket-green\",\n                    \"tags\": \"adjustable, comfort, machine, royal, running, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Juno Jacket\",\n                    \"shortDesc\": \"On colder-than-comfortable mornings, you'll love warming up in the Juno All-Ways Performanc Jacket, designed to compete with wind and chill. Built-in Cocona® technology aids evaporation, while a special zip placket and stand-up collar keep your ne\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052084798\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-green_main_7f692ff8-45b0-4d08-8371-a2044df82752_medium.jpg?v=1575478284\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487310398\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Green\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-green_main_7f692ff8-45b0-4d08-8371-a2044df82752_medium.jpg?v=1575478284\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-green\",\n                    \"tags\": \"green, machine, royal, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384051527742\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"66.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj10-red_main_9e1898b9-9d4a-41df-8dc6-7d31cd23c34e_medium.jpg?v=1575478275\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366485966910\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ10-XS-Red\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj10-red_main_9e1898b9-9d4a-41df-8dc6-7d31cd23c34e_medium.jpg?v=1575478275\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"66.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Tops;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/mars-heattech-trade-pullover-red\",\n                    \"tags\": \"machine, red, royal, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Mars HeatTech™ Pullover\",\n                    \"shortDesc\": \"The Mars HeatTech™ Jacket defense against winter climes so you can play offense in the park, on the trail or in the deck chair. Great for the ski lodge or stadium, it features a wind- and water-resistant outer shell with a draw-cord hood and deep\",\n                    \"category\": \"Tops;;Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033603646\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"56.25\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj02-blue_main_8549c057-4567-4b63-ac2e-2068d345ff28_medium.jpg?v=1575478014\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456279102\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ02-XS-Blue\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj02-blue_main_8549c057-4567-4b63-ac2e-2068d345ff28_medium.jpg?v=1575478014\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"56.25\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/josie-yoga-jacket-blue\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Josie Yoga Jacket\",\n                    \"shortDesc\": \"When your near future includes yoga, the cozy comfort of the Josie Yoga Jacket gets your mind and body ready. Stretchy CoolTech™ fabric with zipper pockets makes this jacket the right gear for studio time or teatime after. • Slate rouched n\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052150334\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-gray_main_3787cf65-8e0a-4540-8f11-6d188980a6eb_medium.jpg?v=1575478285\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487375934\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Gray\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-gray_main_3787cf65-8e0a-4540-8f11-6d188980a6eb_medium.jpg?v=1575478285\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-gray\",\n                    \"tags\": \"gray, machine, royal, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033243198\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-white_main_d8fa2b03-08ff-485c-afd1-b3761e70e9ce_medium.jpg?v=1575478004\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455427134\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-White\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-white_main_d8fa2b03-08ff-485c-afd1-b3761e70e9ce_medium.jpg?v=1575478004\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-white\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033308734\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-red_main_5c76d8d8-ad1a-414f-b6b7-9edccc50b955_medium.jpg?v=1575478005\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455525438\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-red_main_5c76d8d8-ad1a-414f-b6b7-9edccc50b955_medium.jpg?v=1575478005\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-red\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Hoodies & Sweatshirts\",\n                    \"itemGroupId\": \"4384033964094\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"75.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-blue_main_d6ed0a23-7d18-42d4-921c-5669f65a7580_medium.jpg?v=1575478022\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456672318\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ01-S-Blue\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-blue_main_d6ed0a23-7d18-42d4-921c-5669f65a7580_medium.jpg?v=1575478022\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"75.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets;;Hoodies & Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/stellar-solar-jacket-s-blue\",\n                    \"tags\": \"Cold-whether, comfortable, crewneck, Grayson, Hoodie, machine, Sweatshirt, winter, Wool\",\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"shortDesc\": \"Beat the heat and protect yourself from sunrays with the Stellar Solar Jacket. It's loaded with all the engineered features you need for an intense, safe outdoor workout: 100% UV protection, a breathable perforated construction, and advanced moist\",\n                    \"category\": \"Jackets;;Hoodies & Sweatshirts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052412478\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"72.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj07-red_main_7fb57683-fddb-44a9-90aa-fc03536bbd90_medium.jpg?v=1575478289\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487769150\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ07-XS-Red\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj07-red_main_7fb57683-fddb-44a9-90aa-fc03536bbd90_medium.jpg?v=1575478289\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"72.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/orion-two-tone-fitted-jacket-red\",\n                    \"tags\": \"machine, red, royal, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Orion Two-Tone Fitted Jacket\",\n                    \"shortDesc\": \"While you're getting fit, you need a fitted jacket to match. Striking color blocking patterns on hood, shoulders and arms are hallmarks of the Orion Two-Tone Fitted Jacket. They provide eye-catching contrast against the rich, torso tones of this 1\",\n                    \"category\": \"Jackets\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"categoryProducts\",\n      \"typeOfRequest\": \"CATNAV\",\n      \"settings\": {\n       \"merchandisingVersion\": 1739999922000,\n        \"query\": {\n          \"categoryPath\": \"Jackets\"\n        }\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"categoryProducts\",\n      \"typeOfRequest\": \"CATNAV\",\n      \"settings\": {\n       \"merchandisingVersion\": 1739999922000,\n        \"query\": {\n          \"categoryPath\": \"Jackets\"\n        }\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "// WARNING: For POST requests, body is set to null by browsers.\nvar data = JSON.stringify({\n  \"recordQueries\": [\n    {\n      \"id\": \"categoryProducts\",\n      \"typeOfRequest\": \"CATNAV\",\n      \"settings\": {\n        \"merchandisingVersion\": 1739999922000,\n        \"query\": {\n          \"categoryPath\": \"Jackets\"\n        }\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = true;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\r\\n  \\\"recordQueries\\\": [\\r\\n    {\\r\\n      \\\"id\\\": \\\"categoryProducts\\\",\\r\\n      \\\"typeOfRequest\\\": \\\"CATNAV\\\",\\r\\n      \\\"settings\\\": {\\r\\n       \\\"merchandisingVersion\\\": 1739999922000,\\r\\n        \\\"query\\\": {\\r\\n          \\\"categoryPath\\\": \\\"Jackets\\\"\\r\\n        }\\r\\n      }\\r\\n    }\\r\\n  ],\\r\\n  \\\"context\\\": {\\r\\n    \\\"apiKeys\\\": [\\r\\n      \\\"klevu-156925593843210765\\\"\\r\\n    ]\\r\\n  }\\r\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    \"recordQueries\": [\n      {\n        \"id\": \"categoryProducts\",\n        \"typeOfRequest\": \"CATNAV\",\n        \"settings\": {\n          \"merchandisingVersion\": 1739999922000,\n          \"query\": {\n            \"categoryPath\": \"Jackets\"\n          }\n        }\n      }\n    ],\n    \"context\": {\n      \"apiKeys\": [\n        \"klevu-156925593843210765\"\n      ]\n    }\n  })\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "jSU7DlYyJ_eUh63YSP682"
  },
  "description": "This is an example how to fetch product from specific category. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "category-search",
  "legacyHash": "BCHSzfh6TpUYXs0k-2JBF"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=categorySearch&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Overview
[path] Guide/Smart Category Merchandising/

Klevu Smart Category Merchandising is a holistic tool that magically combines rich insights from site-wide search, navigation, purchases and the customer’s current session with strategic business goals.

## Getting Started

- Understanding V2 format by going through API v2 [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
- Implementing APIs to fetch [Category Product Search](docId\:sAj_Ou1oN-35EqA4IEN5D) &#x20;
- Setting [A/B test campaigns](https://help.klevu.com/support/solutions/articles/5000872848-a-b-testing-of-category-merchandising) and fetching specific variant using [A/B Test](docId\:InZJ-jAgpY95OUpu55FD1) APIs
- Integrate [Analytics Events](docId\:MjUDl2Y9O5YbYRM00HWmF)&#x20;


[title] Overview
[path] Guide/Smart Search/

Klevu APIv2 is the latest version of our API for integrating Smart search into your applications for lightning-fast search as , record search results.&#x20;

## JS API Key & Endpoint

You must have a Klevu Search account to use the Klevu API. Please access the 'Shop Info' tab of your Klevu Merchant Centre to retrieve the following credentials.

- **JS API Key** *(readonly key)* for querying indexed data e.g. klevu-156925593843210765
- **APIv2 Cloud Search URL&#x20;**&#x66;or end-point e.g. eucs15v2.ksearchnet.com

If you have multiple stores with Klevu, please note it is likely that each of them will have totally different JS API Keys and subdomains assigned.

## Search URL

When retrieving data for Search, Category Merchandising or Recommendations, Klevu APIv2 utilizes a single endpoint:
https\://\{\{APIv2\_Cloud\_Search\_URL}}/cs/v2/search

Please replace APIv2\_Cloud\_Search\_URL with your own value, which you can find in the Prerequisites above. For example, if your URL is 'eucs15v2.ksearchnet.com' then the correct value is:
https\://eucs15v2.ksearchnet.com/cs/v2/search

The inclusion of 'v2' is important. Without it you will experience degraded performance since your API requests will not be utilizing our Content Delivery Network (CDN).&#x20;

## GET vs POST

The APIv2 Endpoint URL accepts requests in JSON format and also responds with JSON. Requests can be made using either GET or POST, however **we recommend POST**.

:::hint{type="info"}
Because our requests are routed through cloudflare CDN, which has a limit on the size of the payload, we are accepting request payloads up to 8KB.
:::

### Request Object

Every request to APIv2 comprises a structured JSON payload: a request object. The request object is a top level object that comprises a mandatory context and one or both of the suggestions and recordQueries objects. Each HTTP request can contain multiple search queries.

- The context object is for specifying your JS API Key.
- The suggestions object is for requesting suggestions or typeahead results.
- The recordQueries object is for requesting entities such as products or CMS pages.

Please note that despite apiKeys being an array, currently **we only support a single API Key per request.**

A skeleton of the request object looks like this:

:::CodeblockTabs
JSON Request

```json
{
  "request": {
    "context": {
      "apiKeys": ["..."]
    },
    "suggestions": [
      {
        ... suggestions query 1 ...
      },
      {
        ... suggestions query 2 ...
      }
    ],
    "recordQueries":[
      {
        ... record query 1 ...
      },
      {
        ... record query 2 ...
      }
    ]
  }
}

```
:::

### Response Object

When a query is fired, depending on the query objects included in the request, i.e. suggestions and/or record queries, the Klevu Search engine returns a response object containing data for each of these query types, suggestionResults and queryResults.

The meta object contains information on the query related parameters, for example the time taken, the total number of results found, etc.

The skeleton of the response object looks like this:

:::CodeblockTabs
JSON Response

```json
{
  "meta": {
    ...
  },
  "suggestionResults": [
    {
      ... result of suggestions query 1 ...
    },
    {
      ... result of suggestions query 2 ...
    }
  ],
  "queryResults": [
    {
      ... result of record query 1 ...
    },
    {
      ... result of record query 2 ...
    }
  ],
}

```
:::

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs15v2.ksearchnet.com/cs/v2/search",
  "name": "Request and Response example",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "kind": "required",
        "name": "Content-type",
        "type": "string",
        "description": "application/json"
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "9iz3vgfng9gZMSvSz1dKZ",
        "code": "{\n  \"meta\": {\n    \"qTime\": 17,\n    \"responseCode\": 200\n  },\n  \"suggestionResults\": [\n    {\n      \"id\": \"mySuggestionsQuery1\",\n      \"suggestions\": [\n        {\n          \"suggest\": \"workout\"\n        },\n        {\n          \"suggest\": \"wheelset\"\n        }\n      ]\n    },\n    {\n      \"id\": \"mySuggestionsQuery2\",\n      \"suggestions\": [\n        {\n          \"suggest\": \"whiskey\"\n        },\n        {\n          \"suggest\": \"tee-xl-white\"\n        },\n        {\n          \"suggest\": \"tee-m-white\"\n        }\n      ]\n    }\n  ],\n  \"queryResults\": [\n    {\n      \"id\": \"productSearch\",\n      \"meta\": {\n        \"qTime\": 8,\n        \"noOfResults\": 5,\n        \"totalResultsFound\": 77,\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"offset\": 0,\n        \"debuggingInformation\": {},\n        \"notificationCode\": 1,\n        \"searchedTerm\": \"jackets\",\n        \"apiKey\": \"klevu-156925593843210765\",\n        \"isPersonalised\": false\n      },\n      \"records\": [\n        {\n          \"name\": \"Stellar Solar Jacket\",\n          \"id\": \"31366456541246\"\n        },\n        {\n          \"name\": \"Lando Gym Jacket\",\n          \"id\": \"31366487441470\"\n        },\n        {\n          \"name\": \"Ingrid Running Jacket\",\n          \"id\": \"31366455590974\"\n        },\n        {\n          \"name\": \"Juno Jacket\",\n          \"id\": \"31366453067838\"\n        },\n        {\n          \"name\": \"Josie Yoga Jacket\",\n          \"id\": \"31366456279102\"\n        }\n      ],\n      \"filters\": []\n    },\n    {\n      \"id\": \"categorySearch\",\n      \"meta\": {\n        \"qTime\": 7,\n        \"noOfResults\": 1,\n        \"totalResultsFound\": 1,\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"offset\": 0,\n        \"debuggingInformation\": {},\n        \"notificationCode\": 1,\n        \"searchedTerm\": \"accessories\",\n        \"apiKey\": \"klevu-156925593843210765\",\n        \"isPersonalised\": false\n      },\n      \"records\": [\n        {\n          \"name\": \"Accessories\",\n          \"id\": \"category_156704342078\"\n        }\n      ],\n      \"filters\": []\n    }\n  ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "9iz3vgfng9gZMSvSz1dKZ"
  },
  "examples": {
    "languages": [
      {
        "id": "dB7rDPkh27GdX1BEKRpb-",
        "code": "{\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  },\n  \"suggestions\": [\n    {\n      \"id\": \"mySuggestionsQuery1\",\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"w\",\n      \"limit\": 2\n    },\n    {\n      \"id\": \"mySuggestionsQuery2\",\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"whi\",\n      \"limit\": 3\n    }\n  ],\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"jackets\"\n        },\n        \"limit\": 5,\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    },\n    {\n      \"id\": \"categorySearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"accessories\"\n        },\n        \"limit\": 1,\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_CATEGORY\"\n        ]\n      }\n    }\n  ]\n}",
        "language": "none",
        "customLabel": "JSON Request"
      },
      {
        "id": "E8rfGe9Aylw0VLF-Hdda8",
        "code": "curl --request POST\n  --url https://eucs15v2.ksearchnet.com/cs/v2/search\n  --header 'Accept: application/json'",
        "language": "curl",
        "customLabel": ""
      },
      {
        "id": "ouorYFTw1CAg9pYz2OATC",
        "code": "const fetch = require('node-fetch');\n\nlet url = 'https://eucs15v2.ksearchnet.com/cs/v2/search';\nlet options = {\n  method: 'POST',\nheaders: {\n    Accept: 'application/json',\n  }\n};\nfetch(url, options)\n  .then(res => res.json())\n  .then(json => console.log(json))\n  .catch(err => console.error('error:' + err));",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "3lGoraqzx2OjzjAcuL7VS",
        "code": "fetch(\"https://eucs15v2.ksearchnet.com/cs/v2/search\", {\n  \"method\": \"POST\",\n  \"headers\": {\n    \"Accept\": \"application/json\"\n  }\n})\n.then(response => {\n  console.log(response);\n})\n.catch(err => {\n  console.error(err);\n});",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "RBQvREns3vPovnG1FPPH4",
        "code": "import requests\n\nurl = \"https://eucs15v2.ksearchnet.com/cs/v2/search\"\nheaders = {\"Accept\": \"application/json\"}\nresponse = requests.request(\"GET\", url, headers=headers)\nprint(response.text)",
        "language": "python",
        "customLabel": ""
      },
      {
        "id": "NQdyIks4qYUGIcA5IMEpr",
        "code": "const fetch = require('node-fetch');\n\nlet url = 'https://eucs15v2.ksearchnet.com/cs/v2/search';\nlet options = {method: 'POST', headers: {Accept: 'application/json'}};\nfetch(url, options)\n  .then(res => res.json())\n  .then(json => console.log(json))\n  .catch(err => console.error('error:' + err));",
        "language": "ruby",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "dB7rDPkh27GdX1BEKRpb-"
  },
  "description": "",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "request-and-response-example",
  "legacyHash": "aI4T1RrwNNoXLz0BYFtPa"
}
```
:::

### Understanding the response parameters:

| Parameters | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id         | The ID of the record query for which the results are being returned.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| meta       | The meta object contains information on the query related parameters.&#xA;&#xA;**qTime**: The time taken by the Klevu Search engine to fetch the response.&#xA;&#xA;**noOfResults**: The number of results requested to be returned for this query.&#xA;&#xA;**totalResultsFound**: The total number of results found for this query.&#xA;&#xA;**offset**: The index of the first result returned in this response.&#xA;&#xA;**typeOfSearch**: The query type that was executed by Klevu to retrieve the results.&#xA;&#xA;**debuggingInformation**: Information that can be useful for debugging the query. For example, the actual query that was fired by the Klevu Search engine, inclusive of any synonyms or de-compounded words taken into consideration.&#xA;&#xA;**notificationCode**: This may be populated with a code if any actions were taken on the record. Possible values are:<br />* 1: Nothing to report.
* 2: The price of the record is using the base currency.<br />**searchedTerm**: The search term submitted for this query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| records    | The records matching the query. Each record object is a map of key-value pairs, where the key is the name of a field (e.g. id, name, price) and the value of that field stored in the Klevu index. The following fields are included for each record.<br /><br />**id**: The unique identifier of the record within Klevu.<br /><br />**itemGroupId**: The identifier used to group compound products together, eg. the ID of the parent in the case of a configurable product.<br /><br />**name**: The name of your record, eg. the product name or category title.<br /><br />**url**: The fully qualified URL used to access the record in your store.<br /><br />**sku**: The Stock Keeping Unit of the record.<br /><br />**inStock**: Whether or not your record is in stock, 'yes' or 'no'.<br /><br />**price**: The original price of your product, before any discounts. This can be used as 'was price' when used in conjunction with salePrice.<br />salePrice: The actual selling price of your product, or 'now' price when used in conjunction with price. Note that when using filters, the sale price is represented by klevu\_price.<br /><br />**startPrice**: The salePrice of the lowest variant within all those indexed with the same itemGroupId. This can be used if you would like to show 'as low as' price.<br /><br />**toPrice**: The salePrice of the highest variant within all those indexed with the same itemGroupId. This can be used if you would like to show 'from X to Y' price range.<br /><br />**groupPrices**: This field is not always populated and is mostly used in older integrations. It includes the prices of your record in format groupId\:price so you can use your own frontend logic to display prices in realtime. If you are using the B2B group price search parameters described in this documentation, the price and salePrice are automatically calculated so there is no need to use this field in most cases.<br /><br />**currency**: The currency code applicable to the price values being displayed.<br /><br />**category**: A double semicolon ;; separated list of the most specific categories, not including their full path. For example if a record was in 'Mens > Shoes' and 'Mens > Tees', the value would be Shoes;;Tees.<br />klevu\_category: This is mostly for internal purposes, but includes the categorisation of the record within Klevu. For example KLEVU\_PRODUCT;;Shop All;;Bath;;;groupid\_1 @ku\@kuCategory\@ku\@.<br /><br />**shortDesc**: The short description of your record.<br /><br />**rating**: The rating of your product, between 0 and 5.<br /><br />**ratingCount**: The number of ratings given by customers for your product.<br /><br />**image**: The fully qualified URL to the main image of your record.<br /><br />**imageHover**: The fully qualified URL to the secondary image of your record.<br /><br />**swatches**: If your indexed data includes variants with swatch information, this will be provided here as a nested object with the following elements:<br />          --**id**: The Klevu record ID of the variant the swatch represents.<br />          --**color**: The label to be displayed for the swatch, eg. Red&#xA;          \--**swatchImage**: The hex colour or image URL to be displayed as the swatch pattern, eg. #FF0000<br />          --**image**: The image of the product which corresponds to this swatch, eg. a picture of the tshirt in red.&#xA;          \--**numberOfAdditionalVariants**: If there are additional variants which have not been included, the number will be included here, so you can display something like "Also available in 4 other colours"<br />&#xA;**totalVariants**: How many additional variants are available for this product. For example when searching for 'small tshirt', if a product has 3 colours available in small then the value here will be 2. If the search was 'tshirt' then the same record would return a value of 8 if there are 3 colours and 3 sizes of each available.<br /><br />**score**: The score the record has achieved, ie. how relevant it is, which is used for sorting by relevance. This value must be either explicitly requested in fields or using Search Preference enableScores.<br /><br />**klevu\_manual\_boosting**: Any manual score assigned by the merchant. This value must be either explicitly requested in fields or using Search Preference enableScores.<br /><br />**klevu\_bulk\_boosting**: Any manual score assigned by the manual boosting rules. This value must be either explicitly requested in fields or using Search Preference enableScores.<br /><br />**klevu\_selflearning\_boosting**: The machine learning score assigned by the Klevu Search engine. This value must be either explicitly requested in fields or using Search Preference enableScores.<br />brand: The brand of the product, eg. 'Nike'.<br /><br />**tags**: Any tags or keywords Klevu has saved for the record.<br /><br />**typeOfRecord**: The type of record, e.g. KLEVU\_PRODUCT, KLEVU\_CMS, KLEVU\_CATEGORY, etc.<br /><br />**other fields**: There will also be various other fields returned according to the data you have indexed, which will vary from store to store. |









[title] Examples
[path] Guide/Smart Search/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

## Custom Record Type

In addition to Products, Categories and CMS Pages, Klevu APIv2 allows you to search for custom entities.&#x20;

For example, if you want to display results for recipes, articles or physical stores within your search you can do so by utilising the **typeOfRecords** parameter.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Custom Record type",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRecords",
        "type": "Array",
        "description": "Specify the identifier(s) of your custom entity types that you have indexed with Klevu, for example ACME_RECIPE or ACME-STORE."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 8,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"customeEntitySearch1\",\n            \"meta\": {\n                \"qTime\": 5,\n                \"noOfResults\": 1,\n                \"totalResultsFound\": 2,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"fish\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Recipe: Fish and Chips\",\n                    \"klevu_category\": \"ACME_RECIPE  @ku@kuCategory@ku@\",\n                    \"id\": \"recipe_1\",\n                    \"typeOfRecord\": \"ACME_RECIPE\"\n                }\n            ],\n            \"filters\": []\n        },\n        {\n            \"id\": \"customeEntitySearch2\",\n            \"meta\": {\n                \"qTime\": 7,\n                \"noOfResults\": 1,\n                \"totalResultsFound\": 1,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"london\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Shop: London\",\n                    \"klevu_category\": \"ACME-STORE  @ku@kuCategory@ku@\",\n                    \"id\": \"shop_2\",\n                    \"typeOfRecord\": \"ACME-STORE\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"customeEntitySearch1\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"fish\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME_RECIPE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\",\n            \"typeOfRecord\"\n        ]\n      }\n    },\n    {\n      \"id\": \"customeEntitySearch2\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"london\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME-STORE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\",\n            \"typeOfRecord\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"customeEntitySearch1\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"fish\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME_RECIPE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\",\n            \"typeOfRecord\"\n        ]\n      }\n    },\n    {\n      \"id\": \"customeEntitySearch2\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"london\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME-STORE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\",\n            \"typeOfRecord\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"customeEntitySearch1\",\"settings\":{\"query\":{\"term\":\"fish\"},\"limit\":1,\"typeOfRecords\":[\"ACME_RECIPE\"],\"fields\":[\"id\",\"name\",\"typeOfRecord\"]}},{\"id\":\"customeEntitySearch2\",\"settings\":{\"query\":{\"term\":\"london\"},\"limit\":1,\"typeOfRecords\":[\"ACME-STORE\"],\"fields\":[\"id\",\"name\",\"typeOfRecord\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"customeEntitySearch1\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"fish\\\"\\n        },\\n        \\\"limit\\\": 1,\\n        \\\"typeOfRecords\\\": [\\n          \\\"ACME_RECIPE\\\"\\n        ],\\n        \\\"fields\\\": [\\n            \\\"id\\\",\\n            \\\"name\\\",\\n            \\\"typeOfRecord\\\"\\n        ]\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"customeEntitySearch2\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"london\\\"\\n        },\\n        \\\"limit\\\": 1,\\n        \\\"typeOfRecords\\\": [\\n          \\\"ACME-STORE\\\"\\n        ],\\n        \\\"fields\\\": [\\n            \\\"id\\\",\\n            \\\"name\\\",\\n            \\\"typeOfRecord\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"customeEntitySearch1\",\"settings\":{\"query\":{\"term\":\"fish\"},\"limit\":1,\"typeOfRecords\":[\"ACME_RECIPE\"],\"fields\":[\"id\",\"name\",\"typeOfRecord\"]}},{\"id\":\"customeEntitySearch2\",\"settings\":{\"query\":{\"term\":\"london\"},\"limit\":1,\"typeOfRecords\":[\"ACME-STORE\"],\"fields\":[\"id\",\"name\",\"typeOfRecord\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to search for custom record type. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "custom-record-type-1",
  "legacyHash": "HtXP4LSj85Bo7msT-RkvZ"
}
```
:::

### Try it here

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=customRecordType&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Multiple Queries

Klevu APIv2 allows you to request multiple Product, Category, CMS Pages and Custom Entity queries all at the same time. All of these queries are usually fired simultaneously, meaning the total time taken is the duration of the slowest query, rather than the total of all queries.

In the example to the right, a single HTTP request is returning:

- 3x search suggestions
- 3x categories
- 5x products with filters
- 3x different products without filters
- 5x cms pages or recipes (a custom entity)
- 1x store (a custom entity)

Furthermore, all of the configuration and preferences found within this documentation can be applied to each and evey query separately, making an extremely powerful and fast way to display search results.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Multiple Queries",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 21,\n        \"responseCode\": 200\n    },\n    \"suggestionResults\": [\n        {\n            \"id\": \"suggestionSearch\",\n            \"suggestions\": [\n                {\n                    \"suggest\": \"<b>a</b>tomic\"\n                },\n                {\n                    \"suggest\": \"<b>a</b>tomic endurance\"\n                },\n                {\n                    \"suggest\": \"<b>a</b>tomic endurance running\"\n                }\n            ]\n        }\n    ],\n    \"queryResults\": [\n        {\n            \"id\": \"categorySearch\",\n            \"meta\": {\n                \"qTime\": 8,\n                \"noOfResults\": 3,\n                \"totalResultsFound\": 1,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"a\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Accessories\",\n                    \"id\": \"category_156704342078\"\n                }\n            ],\n            \"filters\": []\n        },\n        {\n            \"id\": \"productSearch1\",\n            \"meta\": {\n                \"qTime\": 14,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 447,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"a\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Affirm Water Bottle\",\n                    \"id\": \"31366498222142\"\n                },\n                {\n                    \"name\": \"Cruise Dual Analog Watch\",\n                    \"id\": \"31366496124990\"\n                },\n                {\n                    \"name\": \"Ariel Roll Sleeve Sweatshirt\",\n                    \"id\": \"31366458376254\"\n                },\n                {\n                    \"name\": \"Livingston All-Purpose Tight\",\n                    \"id\": \"31366468010046\"\n                },\n                {\n                    \"name\": \"Livingston All-Purpose Tight\",\n                    \"id\": \"31366467977278\"\n                }\n            ],\n            \"filters\": [\n                {\n                    \"key\": \"tags\",\n                    \"label\": \"Tags\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 192,\n                            \"name\": \"machine\",\n                            \"value\": \"machine\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 143,\n                            \"name\": \"comfortable\",\n                            \"value\": \"comfortable\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 120,\n                            \"name\": \"comfort\",\n                            \"value\": \"comfort\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 116,\n                            \"name\": \"winter\",\n                            \"value\": \"winter\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 106,\n                            \"name\": \"cotton\",\n                            \"value\": \"cotton\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 80,\n                            \"name\": \"Hoodie\",\n                            \"value\": \"Hoodie\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 77,\n                            \"name\": \"Flexible\",\n                            \"value\": \"Flexible\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 76,\n                            \"name\": \"Cold-whether\",\n                            \"value\": \"Cold-whether\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 67,\n                            \"name\": \"Short\",\n                            \"value\": \"Short\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 62,\n                            \"name\": \"royal\",\n                            \"value\": \"royal\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"category\",\n                    \"label\": \"category\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 83,\n                            \"name\": \"Hoodies & Sweatshirts\",\n                            \"value\": \"Hoodies & Sweatshirts\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 81,\n                            \"name\": \"Jackets\",\n                            \"value\": \"Jackets\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 77,\n                            \"name\": \"Pants\",\n                            \"value\": \"Pants\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 71,\n                            \"name\": \"Smart Collection 1\",\n                            \"value\": \"Smart Collection 1\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 69,\n                            \"name\": \"Tees\",\n                            \"value\": \"Tees\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 68,\n                            \"name\": \"Shorts\",\n                            \"value\": \"Shorts\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 59,\n                            \"name\": \"Smart Collection 3\",\n                            \"value\": \"Smart Collection 3\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 53,\n                            \"name\": \"Hoodies\",\n                            \"value\": \"Hoodies\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 42,\n                            \"name\": \"Bras & Tanks\",\n                            \"value\": \"Bras & Tanks\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 39,\n                            \"name\": \"Tanks\",\n                            \"value\": \"Tanks\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"size\",\n                    \"label\": \"Size\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 143,\n                            \"name\": \"Small\",\n                            \"value\": \"Small\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 141,\n                            \"name\": \"Medium\",\n                            \"value\": \"Medium\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 140,\n                            \"name\": \"Large\",\n                            \"value\": \"Large\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 9,\n                            \"name\": \"Free Size\",\n                            \"value\": \"Free Size\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 3,\n                            \"name\": \"S\",\n                            \"value\": \"S\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 2,\n                            \"name\": \"XL\",\n                            \"value\": \"XL\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 2,\n                            \"name\": \"XXL\",\n                            \"value\": \"XXL\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 2,\n                            \"name\": \"medium\",\n                            \"value\": \"medium\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"brand\",\n                    \"label\": \"brand\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 169,\n                            \"name\": \"KSD\",\n                            \"value\": \"KSD\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 144,\n                            \"name\": \"MNH\",\n                            \"value\": \"MNH\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 138,\n                            \"name\": \"KKE\",\n                            \"value\": \"KKE\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 7,\n                            \"name\": \"Klevu Search Demo\",\n                            \"value\": \"Klevu Search Demo\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 1,\n                            \"name\": \"KKE New\",\n                            \"value\": \"KKE New\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"type\",\n                    \"label\": \"Type\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 83,\n                            \"name\": \"Hoodies & Sweatshirts\",\n                            \"value\": \"Hoodies & Sweatshirts\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 77,\n                            \"name\": \"Pants\",\n                            \"value\": \"Pants\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 69,\n                            \"name\": \"Tees\",\n                            \"value\": \"Tees\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 68,\n                            \"name\": \"Shorts\",\n                            \"value\": \"Shorts\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 62,\n                            \"name\": \"Jackets\",\n                            \"value\": \"Jackets\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 42,\n                            \"name\": \"Bras & Tanks\",\n                            \"value\": \"Bras & Tanks\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 18,\n                            \"name\": \"Tanks\",\n                            \"value\": \"Tanks\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 14,\n                            \"name\": \"Bags\",\n                            \"value\": \"Bags\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 10,\n                            \"name\": \"Fitness Equipment\",\n                            \"value\": \"Fitness Equipment\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 9,\n                            \"name\": \"Watches\",\n                            \"value\": \"Watches\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"salePrice\",\n                    \"label\": \"salePrice\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 47,\n                            \"name\": \"29.00\",\n                            \"value\": \"29.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 35,\n                            \"name\": \"39.00\",\n                            \"value\": \"39.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 26,\n                            \"name\": \"32.00\",\n                            \"value\": \"32.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 24,\n                            \"name\": \"42.00\",\n                            \"value\": \"42.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 22,\n                            \"name\": \"24.00\",\n                            \"value\": \"24.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 22,\n                            \"name\": \"28.00\",\n                            \"value\": \"28.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 20,\n                            \"name\": \"48.00\",\n                            \"value\": \"48.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 17,\n                            \"name\": \"45.00\",\n                            \"value\": \"45.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 16,\n                            \"name\": \"57.00\",\n                            \"value\": \"57.00\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 14,\n                            \"name\": \"49.00\",\n                            \"value\": \"49.00\",\n                            \"selected\": false\n                        }\n                    ]\n                }\n            ]\n        },\n        {\n            \"id\": \"productSearch2\",\n            \"meta\": {\n                \"qTime\": 10,\n                \"noOfResults\": 3,\n                \"totalResultsFound\": 419,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"b\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Wayfarer Messenger Bag\",\n                    \"id\": \"31366499991614\"\n                },\n                {\n                    \"name\": \"Prima Compete Bra Top\",\n                    \"id\": \"31366445826110\"\n                },\n                {\n                    \"name\": \"Lucia Cross-Fit Bra\",\n                    \"id\": \"31366444220478\"\n                }\n            ],\n            \"filters\": []\n        },\n        {\n            \"id\": \"cmsAndRecipeSearch\",\n            \"meta\": {\n                \"qTime\": 10,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 7,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"a\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Recipe: Fish and Chips\",\n                    \"id\": \"recipe_1\"\n                },\n                {\n                    \"name\": \"About Us\",\n                    \"id\": \"page_47677767742\"\n                },\n                {\n                    \"name\": \"Recipe: Fish & Chips\",\n                    \"id\": \"page_50756288574\"\n                },\n                {\n                    \"name\": \"Recipe: Fish Pie\",\n                    \"id\": \"page_51008929854\"\n                },\n                {\n                    \"name\": \"Recipe: Fish Pie\",\n                    \"id\": \"recipe_2\"\n                }\n            ],\n            \"filters\": []\n        },\n        {\n            \"id\": \"storeSearch\",\n            \"meta\": {\n                \"qTime\": 10,\n                \"noOfResults\": 1,\n                \"totalResultsFound\": 2,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"a\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Shop: London\",\n                    \"id\": \"shop_2\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  },\n  \"suggestions\": [\n    {\n      \"id\": \"suggestionSearch\",\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"a\",\n      \"limit\": 3\n    }\n  ],\n  \"recordQueries\": [\n    {\n      \"id\": \"categorySearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 3,\n        \"typeOfRecords\": [\n          \"KLEVU_CATEGORY\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"productSearch1\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"filters\": {\n        \"filtersToReturn\": {\n          \"enabled\": true\n        }\n      }\n    },\n    {\n      \"id\": \"productSearch2\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"b\"\n        },\n        \"limit\": 3,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"cmsAndRecipeSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_CMS\",\n          \"ACME_RECIPE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"storeSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME-STORE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    }\n  ]\n}\n",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  },\n  \"suggestions\": [\n    {\n      \"id\": \"suggestionSearch\",\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"a\",\n      \"limit\": 3\n    }\n  ],\n  \"recordQueries\": [\n    {\n      \"id\": \"categorySearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 3,\n        \"typeOfRecords\": [\n          \"KLEVU_CATEGORY\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"productSearch1\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"filters\": {\n        \"filtersToReturn\": {\n          \"enabled\": true\n        }\n      }\n    },\n    {\n      \"id\": \"productSearch2\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"b\"\n        },\n        \"limit\": 3,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"cmsAndRecipeSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_CMS\",\n          \"ACME_RECIPE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    },\n    {\n      \"id\": \"storeSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"a\"\n        },\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"ACME-STORE\"\n        ],\n        \"fields\": [\n            \"id\",\n            \"name\"\n        ]\n      }\n    }\n  ]\n}\n',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]},\"suggestions\":[{\"id\":\"suggestionSearch\",\"typeOfQuery\":\"AUTO_SUGGESTIONS\",\"query\":\"a\",\"limit\":3}],\"recordQueries\":[{\"id\":\"categorySearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":3,\"typeOfRecords\":[\"KLEVU_CATEGORY\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"productSearch1\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]},\"filters\":{\"filtersToReturn\":{\"enabled\":true}}},{\"id\":\"productSearch2\",\"settings\":{\"query\":{\"term\":\"b\"},\"limit\":3,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"cmsAndRecipeSearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_CMS\",\"ACME_RECIPE\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"storeSearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":1,\"typeOfRecords\":[\"ACME-STORE\"],\"fields\":[\"id\",\"name\"]}}]});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  },\\n  \\\"suggestions\\\": [\\n    {\\n      \\\"id\\\": \\\"suggestionSearch\\\",\\n      \\\"typeOfQuery\\\": \\\"AUTO_SUGGESTIONS\\\",\\n      \\\"query\\\": \\\"a\\\",\\n      \\\"limit\\\": 3\\n    }\\n  ],\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"categorySearch\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"a\\\"\\n        },\\n        \\\"limit\\\": 3,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_CATEGORY\\\"\\n        ],\\n        \\\"fields\\\": [\\n            \\\"id\\\",\\n            \\\"name\\\"\\n        ]\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"productSearch1\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"a\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      },\\n      \\\"filters\\\": {\\n        \\\"filtersToReturn\\\": {\\n          \\\"enabled\\\": true\\n        }\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"productSearch2\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"b\\\"\\n        },\\n        \\\"limit\\\": 3,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"cmsAndRecipeSearch\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"a\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_CMS\\\",\\n          \\\"ACME_RECIPE\\\"\\n        ],\\n        \\\"fields\\\": [\\n            \\\"id\\\",\\n            \\\"name\\\"\\n        ]\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"storeSearch\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"a\\\"\\n        },\\n        \\\"limit\\\": 1,\\n        \\\"typeOfRecords\\\": [\\n          \\\"ACME-STORE\\\"\\n        ],\\n        \\\"fields\\\": [\\n            \\\"id\\\",\\n            \\\"name\\\"\\n        ]\\n      }\\n    }\\n  ]\\n}\\n\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]},\"suggestions\":[{\"id\":\"suggestionSearch\",\"typeOfQuery\":\"AUTO_SUGGESTIONS\",\"query\":\"a\",\"limit\":3}],\"recordQueries\":[{\"id\":\"categorySearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":3,\"typeOfRecords\":[\"KLEVU_CATEGORY\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"productSearch1\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]},\"filters\":{\"filtersToReturn\":{\"enabled\":true}}},{\"id\":\"productSearch2\",\"settings\":{\"query\":{\"term\":\"b\"},\"limit\":3,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"cmsAndRecipeSearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_CMS\",\"ACME_RECIPE\"],\"fields\":[\"id\",\"name\"]}},{\"id\":\"storeSearch\",\"settings\":{\"query\":{\"term\":\"a\"},\"limit\":1,\"typeOfRecords\":[\"ACME-STORE\"],\"fields\":[\"id\",\"name\"]}}]})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to search for multiple queries. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "multiple-queries-1",
  "legacyHash": "LVgl8FF_2VsbiDSoYulDr"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=multipleQueries&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Fallback Queries

Sometimes customers will search for something which yields few or no results.

In this scenario, you can either present your customer with a 'no results found' message, or you can use the result of another query to show some records which they may be interested in.

We call this a fallback query.

Any query flagged as isFallbackQuery: true will not execute unless certain criteria are met. With this approach you can present customers with alternative results, without needing to make any additional HTTP requests, and also without the jeopardising performance of the initial query.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Fallback Queries",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "fallbackQueryId",
        "type": "string",
        "description": "The ID of another query which should be fired if the current query yields too few results."
      },
      {
        "kind": "optional",
        "name": "fallbackWhenCountLessThan",
        "type": "Integer",
        "description": "Use this parameter to specify the criteria for when a fallback query will be fired. For example, if you would like a fallback query to fire when you have two results or less, specify a value of '3'."
      },
      {
        "kind": "optional",
        "name": "isFallbackQuery",
        "type": "Boolean",
        "description": "Specify a value of true for any queries that should not be executed until some particular criteria are met, in another query. It is not possible for a fallback query to have its own fallback query."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 15,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"myInitialQuery\",\n            \"meta\": {\n                \"qTime\": 12,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 105,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016334910\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431146046\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Green\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-green\",\n                    \"tags\": \"body-hugging, Green, nylon, Running, Short\",\n                    \"size\": \"Small\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016269374\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431080510\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Purple\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-purple\",\n                    \"tags\": \"body-hugging, nylon, Red, Running, Short\",\n                    \"size\": \"Large\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384016203838\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"45.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366431014974\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WSH12-28-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"45.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-red\",\n                    \"tags\": \"body-hugging, nylon, Red, Running, Short\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Erika Running Short\",\n                    \"shortDesc\": \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384040386622\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"32.50\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465781822\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH03-32-Black\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.5\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/meteor-workout-short-black\",\n                    \"tags\": \"black, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Small\",\n                    \"name\": \"Meteor Workout Short\",\n                    \"shortDesc\": \"Step into the Meteor Workout Short for an incredibly lightweight fitness experience. Its breathable construction and an inner brief provide additional comfort and support, while the adjustable waistband offers the perfect fit to take you to the fi\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384039665726\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"29.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465060926\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH05-32-Gray\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"29.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-gray\",\n                    \"tags\": \"Gray, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"shortDesc\": \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384037830718\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"27.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-black_main_2ef78733-04a5-4345-9f5f-992d0cfffe8d_medium.jpg?v=1575478090\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366462472254\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH12-32-Black\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-black_main_2ef78733-04a5-4345-9f5f-992d0cfffe8d_medium.jpg?v=1575478090\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"27.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-black\",\n                    \"tags\": \"Black, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Small\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"shortDesc\": \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384039796798\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"29.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-black_main_f61ee526-b9d3-4eaa-b7b2-80dc400f31b0_medium.jpg?v=1575478115\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465191998\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH05-32-Black\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-black_main_f61ee526-b9d3-4eaa-b7b2-80dc400f31b0_medium.jpg?v=1575478115\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"29.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-black\",\n                    \"tags\": \"Black, Machine, motion-friendly, Nylon, Relaxed fit, Smooth, Summer, yoga-short\",\n                    \"size\": \"Small\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"shortDesc\": \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384039731262\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"29.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-blue_main_2130114d-06b0-4793-8fc2-bf77411297e4_medium.jpg?v=1575478114\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366465126462\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH05-32-Blue\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-blue_main_2130114d-06b0-4793-8fc2-bf77411297e4_medium.jpg?v=1575478114\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"29.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-blue\",\n                    \"tags\": \"Blue, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Large\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"shortDesc\": \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384037765182\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"27.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-gray_main_4bb28c53-a928-47a0-92ea-ecd303f97dba_medium.jpg?v=1575478089\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366462439486\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH12-32-Gray\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-gray_main_4bb28c53-a928-47a0-92ea-ecd303f97dba_medium.jpg?v=1575478089\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"27.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-gray\",\n                    \"tags\": \"Gray, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Large\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"shortDesc\": \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384037699646\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"27.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-red_main_6c29f610-d5f7-4e1a-bde4-1fb148964be5_medium.jpg?v=1575478088\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366462373950\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH12-32-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-red_main_6c29f610-d5f7-4e1a-bde4-1fb148964be5_medium.jpg?v=1575478088\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"27.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-red\",\n                    \"tags\": \"Cotton, Machine, Relaxed fit, Res, Short, Summer\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"shortDesc\": \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384038322238\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"32.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-blue_main_774a1fbb-9eab-4d4f-9261-f1e0c028b492_medium.jpg?v=1575478097\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366463094846\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH10-32-Blue\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-blue_main_774a1fbb-9eab-4d4f-9261-f1e0c028b492_medium.jpg?v=1575478097\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/sol-active-short-blue\",\n                    \"tags\": \"Blue, Machine, Navy polyster, Relaxed fit, Short, Summer\",\n                    \"size\": \"Small\",\n                    \"name\": \"Sol Active Short\",\n                    \"shortDesc\": \"You'll let your fear go and push your limits in your new Sol Active Short. Featuring ultra-breathable performance fabric and a flat comfort-fit waistband, the Sol Active Short is perfect for high-intensity circuits or high-heat bikram. • Li\",\n                    \"category\": \"Shorts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Shorts\",\n                    \"itemGroupId\": \"4384038256702\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"32.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-green_main_18d664f2-5ba2-421d-b89a-87cb73d86416_medium.jpg?v=1575478095\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366463029310\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MSH10-32-Green\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-green_main_18d664f2-5ba2-421d-b89a-87cb73d86416_medium.jpg?v=1575478095\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/sol-active-short-green\",\n                    \"tags\": \"Green, Machine, Nylon, Relaxed fit, Short, Summer\",\n                    \"size\": \"Large\",\n                    \"name\": \"Sol Active Short\",\n                    \"shortDesc\": \"You'll let your fear go and push your limits in your new Sol Active Short. Featuring ultra-breathable performance fabric and a flat comfort-fit waistband, the Sol Active Short is perfect for high-intensity circuits or high-heat bikram. • Li\",\n                    \"category\": \"Shorts\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"myInitialQuery\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"fallbackQueryId\": \"myFallbackQuery\",\n        \"fallbackWhenCountLessThan\": 3\n      }\n    },\n    {\n      \"id\": \"myFallbackQuery\",\n      \"isFallbackQuery\": true,\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfSearch\": \"FUZZY_OR\"\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"myInitialQuery\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"fallbackQueryId\": \"myFallbackQuery\",\n        \"fallbackWhenCountLessThan\": 3\n      }\n    },\n    {\n      \"id\": \"myFallbackQuery\",\n      \"isFallbackQuery\": true,\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfSearch\": \"FUZZY_OR\"\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"myInitialQuery\",\"settings\":{\"query\":{\"term\":\"short\"},\"typeOfSearch\":\"WILDCARD_AND\",\"fallbackQueryId\":\"myFallbackQuery\",\"fallbackWhenCountLessThan\":3}},{\"id\":\"myFallbackQuery\",\"isFallbackQuery\":true,\"settings\":{\"query\":{\"term\":\"short\"},\"typeOfSearch\":\"FUZZY_OR\"}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"myInitialQuery\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"typeOfSearch\\\": \\\"WILDCARD_AND\\\",\\n        \\\"fallbackQueryId\\\": \\\"myFallbackQuery\\\",\\n        \\\"fallbackWhenCountLessThan\\\": 3\\n      }\\n    },\\n    {\\n      \\\"id\\\": \\\"myFallbackQuery\\\",\\n      \\\"isFallbackQuery\\\": true,\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"typeOfSearch\\\": \\\"FUZZY_OR\\\"\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"myInitialQuery\",\"settings\":{\"query\":{\"term\":\"short\"},\"typeOfSearch\":\"WILDCARD_AND\",\"fallbackQueryId\":\"myFallbackQuery\",\"fallbackWhenCountLessThan\":3}},{\"id\":\"myFallbackQuery\",\"isFallbackQuery\":true,\"settings\":{\"query\":{\"term\":\"short\"},\"typeOfSearch\":\"FUZZY_OR\"}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to fetch results as a part of fall back queries.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "fallback-queries-1",
  "legacyHash": "-RFscIe41HW8rdHOrAj56"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=fallbackQueries&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Hand-Picked Products

Sometimes merchants want to take control over which records are included or excluded, or whether certain records should always take precedence over others.

This can be done via query-time **manual merchandising**.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Hand-picked Queries",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "topIds",
        "type": "Array",
        "description": "Specify any records which should always be displayed at the top of the result set. You can specify a record id to control this at variant level, or a itemGroupId to control this at compound item level.\n\nNote that this is only applicable when the sort order is by 'RELEVANCE'."
      },
      {
        "kind": "optional",
        "name": "includeIds",
        "type": "Array",
        "description": "Specify any records which should be included with the results, even if the Klevu search query did not match them. You can specify a record id to control this at variant level, or a itemGroupId to control this at compound item level."
      },
      {
        "kind": "optional",
        "name": "excludeIds",
        "type": "Array",
        "description": "Use this field to exclude certain records from the search results. You can specify a record id to control this at variant level, or an itemGroupId to control this at compound level."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 12,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 8,\n                \"noOfResults\": 10,\n                \"totalResultsFound\": 105,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Summit Watch\",\n                    \"id\": \"31366496223294\",\n                    \"itemGroupId\": \"4384059031614\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431146046\",\n                    \"itemGroupId\": \"4384016334910\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431014974\",\n                    \"itemGroupId\": \"4384016203838\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431080510\",\n                    \"itemGroupId\": \"4384016269374\"\n                },\n                {\n                    \"name\": \"Meteor Workout Short\",\n                    \"id\": \"31366465781822\",\n                    \"itemGroupId\": \"4384040386622\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465191998\",\n                    \"itemGroupId\": \"4384039796798\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465060926\",\n                    \"itemGroupId\": \"4384039665726\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465126462\",\n                    \"itemGroupId\": \"4384039731262\"\n                },\n                {\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462439486\",\n                    \"itemGroupId\": \"4384037765182\"\n                },\n                {\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462373950\",\n                    \"itemGroupId\": \"4384037699646\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366496223294\"\n          },\n          {\n            \"key\": \"itemGroupId\",\n            \"value\": \"4384052412478\"\n          }\n        ],\n        \"includeIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366496223294\"\n          }\n        ],\n        \"excludeIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366451953726\"\n          }\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"itemGroupId\"\n        ],\n        \"limit\": 10\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366496223294\"\n          },\n          {\n            \"key\": \"itemGroupId\",\n            \"value\": \"4384052412478\"\n          }\n        ],\n        \"includeIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366496223294\"\n          }\n        ],\n        \"excludeIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"31366451953726\"\n          }\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"itemGroupId\"\n        ],\n        \"limit\": 10\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"topIds\":[{\"key\":\"id\",\"value\":\"31366496223294\"},{\"key\":\"itemGroupId\",\"value\":\"4384052412478\"}],\"includeIds\":[{\"key\":\"id\",\"value\":\"31366496223294\"}],\"excludeIds\":[{\"key\":\"id\",\"value\":\"31366451953726\"}],\"query\":{\"term\":\"short\"},\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\",\"itemGroupId\"],\"limit\":10},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"topIds\\\": [\\n          {\\n            \\\"key\\\": \\\"id\\\",\\n            \\\"value\\\": \\\"31366496223294\\\"\\n          },\\n          {\\n            \\\"key\\\": \\\"itemGroupId\\\",\\n            \\\"value\\\": \\\"4384052412478\\\"\\n          }\\n        ],\\n        \\\"includeIds\\\": [\\n          {\\n            \\\"key\\\": \\\"id\\\",\\n            \\\"value\\\": \\\"31366496223294\\\"\\n          }\\n        ],\\n        \\\"excludeIds\\\": [\\n          {\\n            \\\"key\\\": \\\"id\\\",\\n            \\\"value\\\": \\\"31366451953726\\\"\\n          }\\n        ],\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"itemGroupId\\\"\\n        ],\\n        \\\"limit\\\": 10\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"topIds\":[{\"key\":\"id\",\"value\":\"31366496223294\"},{\"key\":\"itemGroupId\",\"value\":\"4384052412478\"}],\"includeIds\":[{\"key\":\"id\",\"value\":\"31366496223294\"}],\"excludeIds\":[{\"key\":\"id\",\"value\":\"31366451953726\"}],\"query\":{\"term\":\"short\"},\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\",\"itemGroupId\"],\"limit\":10},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to merchandise search results using APIs.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "hand-picked-queries",
  "legacyHash": "L4gT0Bt7_WcXUQEzCM1kX"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=handPickedQueries&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Custom Queries

:::hint{type="danger"}
**DEPRECATED:**  The use of `customANDQuery` is being deprecated.&#x20;

For better control over custom queries please review and use [Advanced Filtering](docId\:RbT4zzdIHEIp1lCuk8n-r)
:::

You can even write your own **custom queries** with Klevu search, to take more control over your results. The example to the right shows how you can build a query to filter results by Small or Medium records which are NOT brand "KKE."

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Custom Queries",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "customANDQuery",
        "type": "String",
        "description": "DEPRECATED\n\nThe custom query you would like to fire, which Klevu automatically converts into an appropriate query to be included with the request. Use a - character before the parenthesis to exclude records matching the contained condition.\n\nThis is advanced usage of our API and you may need some help with building these queries, so when you need support please reach out to us via the Community Forum."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 7,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 5,\n                \"noOfResults\": 10,\n                \"totalResultsFound\": 209,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"id\": \"31366456541246\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"id\": \"31366487441470\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"id\": \"31366455590974\",\n                    \"brand\": \"MNH\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Josie Yoga Jacket\",\n                    \"id\": \"31366456279102\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"size\": \"Medium\",\n                    \"name\": \"Hollister Backyard Sweatshirt\",\n                    \"id\": \"31366493438014\",\n                    \"brand\": \"MNH\"\n                },\n                {\n                    \"size\": \"Medium\",\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431014974\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"id\": \"31366456672318\",\n                    \"brand\": \"MNH\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Neve Studio Dance Jacket\",\n                    \"id\": \"31366453461054\",\n                    \"brand\": \"MNH\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Augusta Pullover Jacket\",\n                    \"id\": \"31366455820350\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"name\": \"Augusta Pullover Jacket\",\n                    \"id\": \"31366455951422\",\n                    \"brand\": \"MNH\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"customANDQuery\": \"(size:\\\"Small\\\" OR size:\\\"Medium\\\") AND -(brand:\\\"KKE\\\")\",\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"size\",\n          \"brand\"\n        ],\n        \"limit\": 10\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"customANDQuery\": \"(size:\\\\\"Small\\\\\" OR size:\\\\\"Medium\\\\\") AND -(brand:\\\\\"KKE\\\\\")\",\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"size\",\n          \"brand\"\n        ],\n        \"limit\": 10\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"customANDQuery\":\"(size:\\\"Small\\\" OR size:\\\"Medium\\\") AND -(brand:\\\"KKE\\\")\",\"fields\":[\"id\",\"name\",\"size\",\"brand\"],\"limit\":10},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"customANDQuery\\\": \\\"(size:\\\\\\\"Small\\\\\\\" OR size:\\\\\\\"Medium\\\\\\\") AND -(brand:\\\\\\\"KKE\\\\\\\")\\\",\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"size\\\",\\n          \\\"brand\\\"\\n        ],\\n        \\\"limit\\\": 10\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"customANDQuery\":\"(size:\\\"Small\\\" OR size:\\\"Medium\\\") AND -(brand:\\\"KKE\\\")\",\"fields\":[\"id\",\"name\",\"size\",\"brand\"],\"limit\":10},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to merchandise search results using APIs.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "custom-queries-1",
  "legacyHash": "8x7UcQWyUDkGGLq-BFw_q"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=customQueries&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Multiple Currencies

If your store has multiple currencies and you would like to show different values based on the currency your customer is currently viewing, this can be achieved using the priceFieldSuffix parameter.

When specifying a value for priceFieldSuffix, the following fields in your response data will be replaced with the value indexed with Klevu for the corresponding currency:

- price
- salePrice
- currency

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Multi-currency",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "priceFieldSuffix",
        "type": "String",
        "description": "If you have multiple currency support enabled for your store, this parameter can be used to retrieve prices for a specific currency. For example, if the data you have indexed with Klevu includes prices for a base currency GBP and an additional currency USD, a value of 'GBP' or 'USD' here will display the relevant currency values for your records."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 7,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 5,\n                \"noOfResults\": 1,\n                \"totalResultsFound\": 104,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 2,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"salePrice\": \"45.00\",\n                    \"price\": \"45.00\",\n                    \"name\": \"Erika Running Short\",\n                    \"currency\": \"GBP\",\n                    \"id\": \"31366431146046\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"priceFieldSuffix\": \"USD\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"price\",\n          \"salePrice\",\n          \"currency\",\n          \"storeCurrency\"\n        ],\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"priceFieldSuffix\": \"USD\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"price\",\n          \"salePrice\",\n          \"currency\",\n          \"storeCurrency\"\n        ],\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"priceFieldSuffix\":\"USD\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"price\",\"salePrice\",\"currency\",\"storeCurrency\"],\"limit\":1,\"typeOfRecords\":[\"KLEVU_PRODUCT\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"priceFieldSuffix\\\": \\\"USD\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"price\\\",\\n          \\\"salePrice\\\",\\n          \\\"currency\\\",\\n          \\\"storeCurrency\\\"\\n        ],\\n        \\\"limit\\\": 1,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"priceFieldSuffix\":\"USD\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"price\",\"salePrice\",\"currency\",\"storeCurrency\"],\"limit\":1,\"typeOfRecords\":[\"KLEVU_PRODUCT\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to fetch prices for specific currency.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "multi-currency",
  "legacyHash": "phJkDPOOaGdyZHiqMbG94"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=multiCurrency&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Customer Groups

A common B2B requirement is different product visibility and prices based on a customer group. With Klevu APIv2 you can specify parameters to filter out products which a particular customer should not see, and also show them specific prices if they differ from the base price.

When specifying a value for priceFieldSuffix, the following fields in your response data will be replaced with the value indexed with Klevu for the corresponding currency and group:

- price
- salePrice
- currency

When specifying a value for visibilityGroupID, any records that do not belong to that group will be excluded from the results.

In the example to the right, the same product is indexed with data for currencies 'GBP' and 'USD'. It's visibility is set to groups 'my\_group\_1' and 'my\_group\_3', but not 'my\_group\_2'.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Customer Groups",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "priceFieldSuffix",
        "type": "String",
        "description": "If you have provided different prices for different groups when indexing your store data with Klevu, you can fetch those prices specific to a particular group.\n\nThe format of this parameter is {CURRENCY}-{GROUPID}. For example if the currency you require is USD and your indexed group ID is 'my-group-1', your query should include \"priceFieldSuffix\": \"USD-my-group-1\"."
      },
      {
        "kind": "optional",
        "name": "visibilityGroupID ",
        "type": "string",
        "description": "If you have provided visibility data for each record when indexing your store data with Klevu, you can specify an ID of that group here to exclude all records which do not belong.\n\nThe format of this parameter is {GROUPID}. For example if your indexed group ID is 'my-group-1', your query should include \"visibilityGroupID\": \"my-group-1\"."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 33,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 31,\n                \"noOfResults\": 1,\n                \"totalResultsFound\": 0,\n                \"typeOfSearch\": \"FUZZY_OR\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"priceFieldSuffix\": \"USD-my_group_3\",\n        \"visibilityGroupID\": \"my_group_3\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"price\",\n          \"salePrice\",\n          \"currency\",\n          \"storeCurrency\"\n        ],\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"priceFieldSuffix\": \"USD-my_group_3\",\n        \"visibilityGroupID\": \"my_group_3\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"price\",\n          \"salePrice\",\n          \"currency\",\n          \"storeCurrency\"\n        ],\n        \"limit\": 1,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"priceFieldSuffix\":\"USD-my_group_3\",\"visibilityGroupID\":\"my_group_3\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"price\",\"salePrice\",\"currency\",\"storeCurrency\"],\"limit\":1,\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\n      \\\"settings\\\": {\\n        \\\"priceFieldSuffix\\\": \\\"USD-my_group_3\\\",\\n        \\\"visibilityGroupID\\\": \\\"my_group_3\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"price\\\",\\n          \\\"salePrice\\\",\\n          \\\"currency\\\",\\n          \\\"storeCurrency\\\"\\n        ],\\n        \\\"limit\\\": 1,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"priceFieldSuffix\":\"USD-my_group_3\",\"visibilityGroupID\":\"my_group_3\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"price\",\"salePrice\",\"currency\",\"storeCurrency\"],\"limit\":1,\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to fetch prices specific to customer groups. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "customer-groups-1",
  "legacyHash": "Jc5iLIMiv9JbTyOZR67yD"
}
```
:::

### Try it here

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Initialization
[path] Guide/MOI/

# Initializing a Session

When a shopper starts a chat session the first time, he or she will not have any sessionId assigned to him/her.  At this time, a message with the Klevu API key should be sent to the MOI backend.  If the API key is valid, the backend in its response will return a sessionId for this shopper and a welcome message to be shown to the shopper.

**Request:**

```json

{

	"context": {

		"klevuApiKey": "<store's api key>"

	}

}
```

**Response:**

```json
{

  "data": [{

      "context": {

        "sessionId": "<some session id>",

        "klevuApiKey": "<store's api key>"

      }

    },

    {

      "message": {

        "id": "6aed823a-1ecc-457a-8d60-d32972408d78",

        "type": "text",

        "value": "I am your shopping assistant. How can I help you?",

        "note": null,

        "explain": null,

        "collectFeedback": false

      }

    },

  . . .

   ]

}

```

###  JSON Response Contents 

The initialization respose contains the following datapoints:

**context**: 

| **Parameter** | **Description**                                                                                              |
| ------------- | ------------------------------------------------------------------------------------------------------------ |
| sessionId     | The sessionId assigned to the current user and should be used for any subsequent interactions by this user.  |
| klevuApiKey   | The Klevu API key used for the session                                                                       |



**message:** there can be one or more of this in a single request. When rendering messages on the front, please show them in the order they are provided in the response.&#x20;

Every `message` has the following members:

| **Parameter**   | **Description**                                                                                                                                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id              | Every message is assigned a unique `id`.  This is used when submitting shopper’s feedback for this particular message. We will see an example of the same a bit later in the document.                            |
| type            | In the current version, the value of this remains as "text".                                                                                                                                                      |
| value           | The message you want to show to the shopper.  The value here is usually a plain text but can also contain URLs and therefore the respective html anchors in it.                                                   |
| note            | This is like a fine print or an instruction or a general note that you may want to show as a fine print to the current message.                                                                                   |
| explain         | Why the system has produced the answer it has, the explanation of the same is provided in this element. It details the reasoning the backend system has followed. In our UIs we show them behind the *info* icon. |
| collectFeedback | If set to "true", this is an instruction to the frontend that feedback should be collected for this particular message.                                                                                           |




[title] Handle User Actions
[path] Guide/MOI/



## Filter Selection

As an example, let us assume that the shopper was presented different sizes as options based on the earlier response provided by the Moi backend.

```json
...

     "filter": {

       "settings": {

         "label": "Please select a size:",

         "key": "size",

         "chatFormat": "$VALUE$ please!",

         "chatFormatEmpty": "Any Size would do!"

       },

       "options": [{

           "name": "s",

           "value": "size:s",

           "selected": "false",

           "count": "31"

         },

         {

           "name": "m",

           "value": "size:m",

           "selected": "false",

           "count": "30"

         },

      ...

       ],

       "note": null

     }
...

```

When a shopper selects a filter option, for example, size "s", we expect a request such as the following to be submitted to the Moi backend.

```json
{

  "context": { ... },

  "message": "s please!",

  "filter": {

    "value": "size:s"

  }

}
```

:::hint{type="warning"}
Please note how the `message` is submitted and the `filter` element with the value "**size\:s"** is submitted. This is the value of the `option` that was sent in the original response.&#x20;
:::

If customer chooses two sizes “s” and “m”, the request for the same should look like the following:

```json

{

  "context": { ... },

  "message": "s and m please!",

  "filter": {

    "value": "size:s;size:m"

  }

}
```

:::hint{type="info"}
Please note how the `value` element inside the `filter` element now has two semicolon separated values.
:::





## Product Questions

This particular option requires a special way of handling. When a shopper clicks on this option, in our current (default) interface we open a separate tab, where we allow shoppers to ask questions about the respective product (see below). 



![](https://lh7-us.googleusercontent.com/LYyQlIitm5DmtJkD01FQKJFNgVoxGSnkNSraMRZE0FG1QqoPseqZKFEK_bDFZDvscg7dCkvscrVQ6LqgHHiVA-DLkQTxdHXHG-EaCnvpqnSDP8ViGYoIvFH9GK6Fs2U-mpRI3-N7innp7JtnZHToG60)

Within this new tab, now when a shopper asks a question, a request such as the following should be made:

**Request:**

```json
{

  "context": {

    "sessionId": "<sessionId>",

    "klevuApiKey": "<store's api key>",

    "url": "<url of the product>",

    "productId": "39941324767325",

    "mode": "product-specific-question"

  },

  "message": "what is the material?"

}


```

Here, as can be seen, we have included three more parameters in the `context` as well as the shopper's question as `message`

| Parameter | Description                                                                       |
| --------- | --------------------------------------------------------------------------------- |
| url       | The respective product's `url`                                                    |
| productId | The respective product's `id`                                                     |
| mode      | Must have the value "**product-specific-question"**                               |
| message   | The customers question &#xA;\*Note: must be sent  outside of the `context` clause |



**Response:**

The Moi backend produces a standard response as it does for any other requests.

```json
{

  "data": [{

      "context": {

        "mode": "product-specific-question",

        "productId": "39941324767325",

        "url": "<url of the product>",

        "sessionId": "<sessionId>",

        "klevuApiKey": "<store's api key>"

      }

    },

    {

      "message": {

        "id": "627cbfb7-c239-4b45-93b0-1f45b3c41037",

        "type": "text",

        "value": "The Uptown Messenger Purse is made of faux leather.",

        "note": null,

        "explain": null,

        "collectFeedback": true

      }

    },

    ...

  ]

}


```





## Product Click

It could be as easy as taking customers to the respective product URL, however, the Moi backend needs to know the products that the shoppers are clicking on to collect analytics events and provide:&#x20;

1. Personalized search experience&#x20;
2. Reports on conversions that were driven by the Moi application.

For this reason, when a shopper *clicks on a product*, we ask you to submit the following request:

**Request:**

```json
{

  "context": {

    "sessionId": "<sessionId>",

    "klevuApiKey": "<store's api key>"

  },

  "product": {

    "id": "<id of the product>",

    "intent": "redirect",

    "context": {

      "url": "<url of the product>"

    }

  }

}


```



**Response:**

```json
{

  "data": [{

      "context": {

        "sessionId": "<sessionId>",

        "klevuApiKey": "<store's api key>"

      }

    },

    {

      "genericOptions": { ... }

    },

    {

      "actions": {

        "actions": [{

          "type": "redirectToUrl",

          "context": {

            "link": "<url of a page / product>"

          }

        }]

      }

    }

  ]

}




```

##

## Feedback

It is important to get shopper feedback on the responses the Moi engine produces.&#x20;

For example, not integrated in Moi but in another application of ours, currently, we show the thumbs **up** and **down** as below:

::Image[]{src="https://lh7-us.googleusercontent.com/_x6DDKg0mfHUdYeKmCGIF0M0F5cxmk-LGWwodFtc3cS3W7Z4J7C6iCF2g6SZgvaLncWwtMsPp2_wvzRALgj04mWeA-I0kO5Pt63548ET9GCZbKGiSTl0OqbbXLgAFwF03jYjuexrPTfH40C8q5frj28" size="80" width="501" height="206" position="center"}

### **Feedback Needed**

Every `message` we return would have an `id` associated with it and an element called `collectFeedback` with its value either set to "**true"** or "**false"**. 

If it is set to "**true"**, we request you to collect feedback from the shopper.

```json
...

    {

      "message": {

        "id": "6aed823a-1ecc-457a-8d60-d32972408d78",

        "type": "text",

        "value": "I am your shopping assistant. How can I help you?",

        "note": null,

        "explain": null,

        "collectFeedback": false

      }

    },

...

```

Once the feedback is collected, it can be sent as the following request. 

### **Send Feedback**

:::hint{type="warning"}
**Important** 

1. The endpoint to submit feedback is different.
2. the `messageId` here must be the same as the `id` of the message sent in the response. The value of the `thumbs` parameter must be either "**UP"** or "**DOWN"**.
:::

**POST** [https://moi-ai.ksearchnet.com/chat/feedback](https://moi-ai.ksearchnet.com/chat/feedback)  

```json
{

    "context": { ... },

    "feedback": {

        "messageId": "a75715e0-70d7-4741-b8b2-06710e6b36bb",

        "thumbs": "DOWN"

    }

}


```


[title] Smart Category Merchandising
[path] Guide/

Klevu helps ecommerce teams thrive. With Klevu’s Smart Category Merchandising, long manual processes and missed merchandising opportunities are behind you.

## Getting Started

- Understanding Klevu's API [Overview](docId\:cZeodl0sKcuv-18IPupLr) format and prerequisites.
- Fetching the Products assigned in specific categories [Category Product Search](docId\:sAj_Ou1oN-35EqA4IEN5D)&#x20;
- &#x20;[A/B Test](docId\:InZJ-jAgpY95OUpu55FD1) to fetch products from specific category merchandising campaign.
- Integrate [Analytics Events](docId\:MjUDl2Y9O5YbYRM00HWmF)&#x20;


[title] UUID
[path] Guide/Analytics Tracking/

The UUID (Universally Unique Identifier) generation endpoint is designed to create a unique identifier that is used exclusively for reporting analytics data within the Klevu platform. This UUID also plays a crucial role in identifying and correlating conversion data, providing a seamless link between user interactions and the resulting analytics.

:::ApiMethodV2
```json
{
  "name": "Generate UUID",
  "method": "POST",
  "url": "https://stats.ksearchnet.com/analytics/uuid",
  "description": "End-point returns the ip address and uuid for a given request. ",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "P_HFKyvUbdsK_s4Ei_TK5",
        "language": "curl",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/uuid',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "customLabel": ""
      },
      {
        "id": "yGEtq5zGT-7c0ZQ4zhfIM",
        "language": "nodejs",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://stats.ksearchnet.com/analytics/uuid',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "P_HFKyvUbdsK_s4Ei_TK5"
  },
  "results": {
    "languages": [
      {
        "id": "h23L4-uKkvzWnzOgHlin5",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"ip_address\": \"X.X.X.X\",\n    \"klevu_uuid\": \"0ff61cc7-4a55-4b3a-b9f8-975ea2b248ea\"\n}"
      }
    ],
    "selectedLanguageId": "h23L4-uKkvzWnzOgHlin5"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "generate-uuid",
  "legacyHash": "55hhLKalwzVr4h-jOmtY4"
}
```
:::


[title] MOI
[path] Guide/

MOI, which means ‘hi’ in Finnish, is a search conversations AI chat tool.&#x20;

MOI is smarter than your average chatbot, built using a clever mix of Klevu AI and Open AI, and is designed to improve the on-site search experience and challenge what’s possible within conventional search.

The APIs documented in this section will enable you to integrate and build your own conversational search appliance!

## Getting Started

- Read the [Overview](docId\:YMqkb0o6mAoIW_n3SOgHE) to understand the prerequisites and key components of integration.
- [Initialization](docId:4DvEJmIjtoKWl8DVWFbW1) of the session to begin conversing with MOI.
- Learn how to construct and [Send a Message](docId\:zvJ9H9HVVwMaOTcy_LhmH) request.
- [Handle User Actions](docId\:KJHFxBHmFgCBntImUHxkJ) and input from the conversation.


[title] V1 (deprecated)
[path] Guide/Smart Category Merchandising/

:::hint{type="warning"}
The v1 APIs are now deprecated! If you are building a new implementation, we strongly recommend going through V2 by visiting [Overview](docId:47rc6vWH1lNhqPTJwUuw9)&#x20;
:::

Using Klevu’s category navigation API, you can now retrieve products for your individual categories, where the order of products is decided by Klevu’s trend-driven intelligent algorithms. If you have setup merchandising rules in the Klevu Merchant Center, all your settings are respected and the order of products is decided accordingly. The continuous learning in Klevu’s backend ensures regular updates on individual category pages reflecting the changing trends of your website.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<cloudSearchURL>/cloud-search/n-search/search",
  "name": "Record search",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "ticket",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "term",
        "type": "string",
        "description": "This should always be set to \" * \" ."
      },
      {
        "kind": "required",
        "name": "isCategoryNavigationRequest",
        "type": "Boolean",
        "description": "This should always be set to true."
      },
      {
        "kind": "required",
        "name": "category",
        "type": "Integer",
        "description": "Hierarchy of the category for which the query is being issued.\n\ne.g. Gifts;Gifts For;Gifts for Him\nUse \";\" as a separator between a parent and its child category.\n\nIt is important that the complete hierarchy of a category is supplied. This is to make sure the results from the correct heirarchy are retrieved."
      },
      {
        "kind": "required",
        "name": "sv",
        "type": "Number",
        "description": "The sv parameter is used for indicating which version of the Klevu Magento plugin you are using (e.g. 1.2.5). In case of a non-magento store, please use the constant “20.0.0”"
      },
      {
        "kind": "optional",
        "name": "paginationStartsFrom",
        "type": "Integer",
        "description": "Index of the first record to be fetched.If for example showing 12 results per page, use the index 12 for the second page and 24 for the third page and so on."
      },
      {
        "kind": "optional",
        "name": "noOfResults",
        "type": "Integer",
        "description": "Indicates the number of records to be fetched. If for example, paginationStartsFrom is set to 0, it will obtain results from 0."
      },
      {
        "kind": "optional",
        "name": "enableFilters",
        "type": "Boolean",
        "description": "If set to true, filters relevant to the search results are retrieved and included in the response. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "enableMultiSelectFilters",
        "type": "Boolean",
        "description": "If set to true, we treat different values of a filter as checkboxes. Otherwise, if set to false, they are treated as radio buttons.\n\ne.g. color:green;;color:white;;brand:nike\nWhen set to true, it finds products with either green OR white color with the brand nike. When set to false, it finds products with both green AND white color AND brand nike. Default value is false. "
      },
      {
        "kind": "optional",
        "name": "applyFilters",
        "type": "string",
        "description": "Tells Klevu which filters to apply on the search results. In case of multiple filters, please use the double semicolon (;;) as the delimiter.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters.\n\ne.g. color:green;;color:white;;brand:nike"
      },
      {
        "kind": "optional",
        "name": "maxNoOfValuesInAFilter",
        "type": "Integer",
        "description": "Number of values to return for each filter. The default is 50. "
      },
      {
        "kind": "optional",
        "name": "sortOrder",
        "type": "string",
        "description": "If you want to sort results in certain order, please use one of the following values:\n- rel for Relevance,\n- lth for Price: Low to High,\n- htl for Price: High to Low. \nThe default value is rel. "
      },
      {
        "kind": "optional",
        "name": "showOutOfStockProducts",
        "type": "Boolean",
        "description": "True to include out of stock products in the search result set, false otherwise. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "fetchMinMaxPrice",
        "type": "Boolean",
        "description": "If set to true, it returns the minimum and maximum prices found for the obtained search results. This can be used, for example, for displaying price slider. If set to false, Klevu will return price ranges (e.g. 0-500, 500-1000 etc.). The price range intervals are dynamically generated by Klevu. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "priceFieldSuffix",
        "type": "string",
        "description": "If you are a shopify plus customer with the multicurrency feature enabled, you can now provide a currency (other than the base currency of your store), to fetch prices in that currency. If in case the prices are not available in the supplied currency, Klevu will return prices in the base currency of the store. e.g. priceFieldSuffix=USD"
      },
      {
        "kind": "optional",
        "name": "visibility",
        "type": "string",
        "description": "Always set this parameter to search to include products with the visibility of search to be included in the result set. The default value is search. "
      },
      {
        "kind": "optional",
        "name": "optionalFilters",
        "type": "string",
        "description": "A parameter to enable personalisation. It instructs Klevu to boost products with the filter values specified here. In case of multiple filters, please use the double semicolon (;;) as a delimiter\n\nWith each filter value, one can assign a boost score.\n\nFor example, if in past a user was seen preferring green color products over any other color and brand to be nike, one can specify the optionalFilters as the following:\n\ne.g. color:green^10;;brand:nike^3.0\n\nHere, use ;; as a delimiter between two filter values and a score between 1 and 100 to boost filter options.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters."
      },
      {
        "kind": "optional",
        "name": "responseType",
        "type": "string",
        "description": "Type of response to be returned. Possible values are xml or json. The default value is xml. "
      },
      {
        "kind": "optional",
        "name": "lsqt",
        "type": "string",
        "description": "When you receive a response for a search query, look at the value of the typeOfQuery element under the metaData section. When you fire a subsequent query (e.g. to apply additional filters, or to obtain results for the next page), pass this value as the value of the lsqt (last search query type) parameter.  Possible values are WILDCARD_AND, FUZZY_AND, OR, FUZZY_OR. "
      },
      {
        "kind": "optional",
        "name": "fl",
        "type": "string",
        "description": "When Klevu returns search results, the response has certain fields for each record included. If you like to retrieve only a set of selected filters, use a list of comma separated field names."
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "{\n    \"meta\": {\n        \"layoutId\": \"\",\n        \"layoutType\": \"\",\n        \"noOfResults\": 2,\n        \"paginationStartFrom\": 0,\n        \"powerdByLogo\": \"\",\n        \"totalResultsFound\": 9,\n        \"typeOfQuery\": \"WILDCARD_AND\",\n        \"storeBaseCurrency\": \"GBP\",\n        \"notificationCode\": 1,\n        \"term\": \"*\",\n        \"excludeIds\": null,\n        \"isPersonalised\": false,\n        \"idsUsedForPersonalisation\": null\n    },\n    \"result\": [\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Watches\",\n            \"itemGroupId\": \"4384059195454\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"49.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg01-bk-0_34e7622a-503f-42f7-8e63-a57d758cf293_medium.jpg?v=1575478386\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366496419902\",\n            \"imageHover\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg01-bk-0_1024x1024_f5db396b-312b-49e3-aa4d-d6731e17d7b1_medium.jpg?v=1575478386\",\n            \"sku\": \"24-MG01\",\n            \"brand\": \"KKE\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg01-bk-0_34e7622a-503f-42f7-8e63-a57d758cf293_medium.jpg?v=1575478386\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"49.0\",\n            \"oldPrice\": \"49.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Watches  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/endurance-watch\",\n            \"tags\": \"Digital, LED, watch\",\n            \"size\": \"Free Size\",\n            \"name\": \"Endurance Watch\",\n            \"shortDesc\": \"It's easy to track and monitor your training progress with the Endurance Watch. You'll see standard info like time, date and day of the week, but it also functions for the serious high-mileage athete: lap counter, stopwatch, distance, heart rate,\",\n            \"category\": \"Watches\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        },\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Watches\",\n            \"itemGroupId\": \"4384058769470\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"92.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg02-bk-0_e6375bd6-e9b3-41ad-ae00-b6ee4457023b_medium.jpg?v=1575478380\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366495961150\",\n            \"imageHover\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg02-bk-0_1024x1024_42c6e9b6-bf83-4bcc-825b-f532eeda29a3_medium.jpg?v=1575478380\",\n            \"sku\": \"24-MG02\",\n            \"brand\": \"KKE\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg02-bk-0_e6375bd6-e9b3-41ad-ae00-b6ee4457023b_medium.jpg?v=1575478380\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"92.0\",\n            \"oldPrice\": \"92.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Watches  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/dash-digital-watch\",\n            \"tags\": \"dash, digital, watch\",\n            \"size\": \"Free Size\",\n            \"name\": \"Dash Digital Watch\",\n            \"shortDesc\": \"The Dash Digital Watch will challenge you to push harder and longer. Log workouts by date, average, and segment times, and recharge by setting hydration and nutrition alarms. This watch is styled with a sleek, square face and durable rubber strap\",\n            \"category\": \"Watches\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        }\n    ],\n    \"filters\": [],\n    \"price\": {\n        \"min\": \"\",\n        \"max\": \"\",\n        \"start\": \"\",\n        \"end\": \"\"\n    },\n    \"autoComplete\": [],\n    \"popularTerm\": [],\n    \"pages\": [],\n    \"categories\": [],\n    \"popularProducts\": [],\n    \"recentlyViewedProducts\": [],\n    \"ranges\": [],\n    \"error\": {\n        \"errorMessage\": \"\"\n    }\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "4UdTvpbDc3I-CZd-C-QoP",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15.ksearchnet.com/cloud-search/n-search/search?ticket=klevu-156925593843210765&term=*&isCategoryNavigationRequest=true&category=KLEVU_PRODUCT%20watches&sv=20.0.0&paginationStartsFrom=0&noOfResults=2&enablePartialSearch=false&enableFilters=false&enableMultiSelectFilters=false&showOutOfStockProducts=true&responseType=json',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "4UdTvpbDc3I-CZd-C-QoP"
  },
  "description": "Use this API method if you want not only the record IDs but also other details associated with the matching records. The method allows you to retrieve facets and autosuggestions as well.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "record-search",
  "legacyHash": "CLFOnnNq8906mSbQ_L4vO"
}
```
:::


[title] Configurations
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Merchants can create and manage multiple Klevu Recommendation banners via our KMC (Klevu Merchant Centre). The configuration via KMC includes the page type, the banner type and even the template to render the banner.

Our recommended approach to display these banners created via the KMC is to use our [HTML Div Integration](https://support.klevu.com/knowledgebase/integration-steps-for-recommendations/) approach, which includes handling of API calls and banner rendering out of the box. You can also retrieve the KMC banner configuration via an API call and process it however you like.

This API call uses a simple GET request with no payload, and since it is intended for use on the frontend there is no authentication required

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://config-cdn.ksearchnet.com/recommendations/klevu-158755634955912036/settings/3a5580bf-c5b2-407e-acac-4a58ae730b64",
  "name": "Get recommendation configuration",
  "method": "GET",
  "request": {
    "pathParameters": [
      {
        "kind": "optional",
        "name": "BASE_PATH",
        "type": "string",
        "description": "A static base url to retrieve Klevu Recommendation configuration from: https://config-cdn.ksearchnet.com"
      },
      {
        "kind": "optional",
        "name": "JS_API_KEY",
        "type": "string",
        "description": "Your public Klevu JS API Key."
      },
      {
        "kind": "optional",
        "name": "RECS_ID",
        "type": "string",
        "description": "The unique ID of your Recommendation banner, which you can find within the KMC.\n"
      }
    ],
    "queryParameters": [
      {
        "name": "pid",
        "kind": "optional",
        "type": "string",
        "description": "The unique identifier of the record within Klevu.",
        "children": []
      },
      {
        "name": "gpid",
        "kind": "optional",
        "type": "string",
        "description": "The identifier used to group compound products together, eg. the ID of the parent in the case of a configurable product",
        "children": []
      },
      {
        "name": "cp",
        "kind": "optional",
        "type": "string",
        "description": "This is the complete hierarchy of the category being visited. For example, Jewellery;Rings;Stackable Rings. Please note the use of a semicolon as the separator between a parent and a child category.",
        "children": []
      },
      {
        "name": "sids",
        "kind": "optional",
        "type": "string",
        "description": "The SegmentIDs (segmentInfo.segments) if using recommendation segmentation.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "hLEZ8xh-V9GIIEzwDwmhA",
        "code": "{\n    \"metadata\": {\n        \"title\": \"Recently Viewed By You\",\n        \"recsKey\": \"3a5580bf-c5b2-407e-acac-4a58ae730b64\",\n        \"pageType\": \"HOME\",\n        \"logic\": \"RECENTLY_VIEWED\",\n        \"maxProducts\": 5,\n        \"productThreshold\": 1,\n        \"enabled\": true\n    },\n    \"search\": {\n        \"basePath\": \"eucs19v2.ksearchnet.com/cs/v2/search\",\n        \"payload\": \"{\\\"recordQueries\\\":[{\\\"id\\\":\\\"klevuRECSItemList\\\",\\\"typeOfRequest\\\":\\\"SEARCH\\\",\\\"settings\\\":{\\\"typeOfRecords\\\":[\\\"KLEVU_PRODUCT\\\"],\\\"limit\\\":5}}]}\"\n    },\n    \"templates\": {\n        \"base\": \"<% var metadata = data.metadata; var logic = (metadata.logic) ? metadata.logic : \\\"\\\"; var pageType = (metadata.pageType) ? metadata.pageType : \\\"\\\"; var recsKey = (metadata.recsKey) ? metadata.recsKey : \\\"\\\"; var title = (metadata.title) ? metadata.title : \\\"\\\"; %>    <div class=\\\"kuRECSContainer\\\" data-logic=\\\"<%= logic %>\\\" data-recskey=\\\"<%= recsKey %>\\\" data-page-type=\\\"<%= pageType %>\\\">        <% var recommendationItemList = klevu.getObjectPath(data,\\\"query.klevuRECSItemList.result\\\");%>            <% if(recommendationItemList && recommendationItemList.length) { %>                <div class=\\\"kuRECSHeader\\\">                    <h3 class=\\\"kuRECSTitle\\\" title=\\\"<%= klevu.dom.helpers.escapeHTML(title) %>\\\">                        <%= title %>                            </h3>                        </div>                    <div class=\\\"kuRECSWrap\\\">                        <div class=\\\"kuRECSResults\\\">                            <div class=\\\"kuRECSResultsInner\\\">                                <% helper.each(recommendationItemList, function(key, item){ %>                                    <div class=\\\"kuRECS-itemWrap kuRECSItem\\\" data-id=\\\"<%= item.id %>\\\">                                        <div class=\\\"kuRECS-item\\\">                                            <div class=\\\"kuRECS-itemImg\\\">                                                <a title=\\\"<%= klevu.dom.helpers.escapeHTML(item.name) %>\\\" href=\\\"<%= item.url %>\\\" data-id=\\\"<%= item.id %>\\\" class=\\\"kuRECSItemClick kuRECSImg\\\">                                                    <img src=\\\"<%= item.image %>\\\" origin=\\\"<%= item.image %>\\\" alt=\\\"<%= klevu.dom.helpers.escapeHTML(item.name) %>\\\" onerror=\\\"klevu.dom.helpers.cleanUpProductImage(this)\\\" class=\\\"prodImg\\\" width=\\\"100%\\\">                                                </a>                                            </div>                                            <div class=\\\"kuRECS-itemDesc\\\">                                                <a title=\\\"<%= klevu.dom.helpers.escapeHTML(item.name) %>\\\" href=\\\"<%= item.url %>\\\" data-id=\\\"<%= item.id %>\\\" class=\\\"kuRECSItemClick kuRECSTitle\\\">                                                    <%= item.name %>    hghfghfghfghgfhfghfg                                                    </a>                                                    <div class=\\\"kuRECS-itemPrice\\\">                                                        <% if(item.ondiscount && item.ondiscount == \\\"true\\\") { %>                                                            <% if(item.salePrice ) { %>                                                                <div class=\\\"kuSalePrice kuSpecialPrice\\\">                                                                    <%=helper.processCurrency(item.currency,parseFloat(item.salePrice) )%>                                                                        </div>                                                                    <% } %>                                                                        <% if(item.price) { %>                                                                            <div class=\\\"kuOrigPrice\\\">                                                                                <%=helper.translate(\\\"Original price %s\\\",helper.processCurrency(item.currency,parseFloat(item.price)))%>                                                                                    </div>                                                                                <% } %>                                                                                    <% } else { %>                                                                                        <% if(item.salePrice ) { %>                                                                                            <div class=\\\"kuSalePrice\\\">                                                                                                <%=helper.processCurrency(item.currency,parseFloat(item.salePrice) )%>                                                                                                    </div>                                                                                                <% } %>                                                                                                    <% } %>                                                                                                        </div>                                                                                                    </div>                                                                                                <div class=\\\"kuRECSItemBottom\\\">                                                                                                    <button data-id=\\\"<%= item.id %>\\\" data-qty=\\\"1\\\" data-url=\\\"<%= item.url %>\\\" class=\\\"kuRECSAddToCartBtn\\\">Add to Cart                                                                                                    </button>                                                                                                </div>                                                                                            </div>                                                                                            </div>                                                                                        <% }) %>                                                                                            </div>                                                                                        </div>                                                                                    </div>                                                                                <% } %>                                                                                    </div>\"\n    },\n    \"styles\": {\n        \"base\": \".kuRECSContainer{  position:relative;  margin:15px 0px;}.kuRECSContainer .kuRECSHeader .kuRECSTitle{  display:block;  font-size:18px;  font-weight:bold;  margin:20px 0px;  overflow:hidden;  white-space:nowrap;  text-overflow:ellipsis;}.kuRECSContainer .kuRECSWrap{  max-width:100%;  position:relative;  padding:0px;  box-sizing:border-box;  font-family:inherit;  overflow:hidden;}.kuRECSContainer .kuRECSWrap *{  outline:none;}.kuRECSContainer .kuRECSResults{  width:100%;  max-width:100%;  overflow:auto;}.kuRECSContainer .kuRECSResultsInner{  transition:-ms-transform 0.5s ease 0s, -webkit-transform 0.5s ease 0s, transform 0.5s ease 0s;  position:relative;  white-space:nowrap;  transition:all 0.5s ease;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemWrap{  display:inline-block;  margin:12px;  margin-left:0px;  vertical-align:top;  width:180px;  border:1px solid #efefef;  border-radius:2px;}.kuRECSContainer .kuRECSResultsInner .kuRECS-item{  margin:0 auto;  padding:12px;  background:#FFF;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemImg{  display:flex;  justify-content:center;  align-items:center;  flex-direction:column;  width:100%;  height:210px;}.kuRECSContainer .kuRECSResultsInner a.kuRECSImg img{  max-width:100%;  height:auto;  width:auto;  display:inline-block;  margin:0 auto;}.kuRECSContainer .kuRECSResultsInner a.kuRECSTitle{  font-size:16px;  font-weight:bold;  text-decoration:none;  overflow:hidden;  white-space:nowrap;  text-overflow:ellipsis;  display:block;  color:#000;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemDesc{  margin-top:12px;  box-sizing:border-box;  overflow:hidden;  white-space:nowrap;  text-overflow:ellipse;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemTag{  color:rgba(0, 0, 0, 0.5);  line-height:110%;  margin-bottom:5px;  min-height:20px;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemSku{  color:rgba(0, 0, 0, 0.5);  font-size:80%;  line-height:110%;  margin-bottom:5px;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemPrice{  font-size:12px;  color:#545454;  margin-bottom:4px;  margin-top:4px;}.kuRECSContainer .kuRECSResultsInner .kuRECS-itemPrice .kuSalePrice{  overflow:hidden;  white-space:nowrap;  text-overflow:ellipsis;}.kuRECSContainer .kuRECSResultsInner .kuRECSAddToCartBtn{  border:0px;  width:100%;  padding:6px;  cursor:pointer;  margin-top:8px;  background:#ececec;  color:#000;  border-radius:2px;}.kuRECSContainer .kuRECSResultsInner .kuRECSAddToCartBtn:hover{  background:#333333;  color:#ececec;}\"\n    },\n    \"scripts\": {\n        \"recsObject\": null\n    }\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "hLEZ8xh-V9GIIEzwDwmhA"
  },
  "examples": {
    "languages": [
      {
        "id": "aDC91fZYiMm5gOJ6UmaDw",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://config-cdn.ksearchnet.com/recommendations/klevu-158755634955912036/settings/3a5580bf-c5b2-407e-acac-4a58ae730b64',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "ekPWzSrWql1wilbus-ULj",
        "code": "var data = \"\";\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"GET\", \"https://config-cdn.ksearchnet.com/recommendations/klevu-158755634955912036/settings/3a5580bf-c5b2-407e-acac-4a58ae730b64\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "WVs1Y_gLp99--DnVmHVhn",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nRequest request = new Request.Builder()\n  .url(\"https://config-cdn.ksearchnet.com/recommendations/klevu-158755634955912036/settings/3a5580bf-c5b2-407e-acac-4a58ae730b64\")\n  .method(\"GET\", null)\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "vANTuFjc8FB1i6AVFp_Ev",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://config-cdn.ksearchnet.com/recommendations/klevu-158755634955912036/settings/3a5580bf-c5b2-407e-acac-4a58ae730b64',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "xv6ofmpD0KlXxrB8lAQPI",
        "language": "none",
        "code": "",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ekPWzSrWql1wilbus-ULj"
  },
  "description": "The end-point is used for retrieving the recommendation template configuration set in Klevu dashboard. ",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "get-recommendation-configuration",
  "legacyHash": "PTZh1h4rZYa5CmrCk8Gxr"
}
```
:::

**Understanding the response: &#x20;**

| **Parameters**            | **Description**                                                                                                                                                                                                                                     |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| metadata.title            | The title of the Recommendation Banner, eg. "Our newest arrivals!".                                                                                                                                                                                 |
| metadata.recsKey          | The unique identifier of the banner. This will match the value of RECS\_ID in the request, eg. 3a5580bf-c5b2-407e-acac-4a58ae730b64.                                                                                                                |
| metadata.pageType         | The page type this banner should be displayed on. This will be one of:<br />* **HOME:** Homepage.
* **CATEGORY:** Collection or Category Listing Page.
* **PRODUCT:** Product Detail Page.
* **CHECKOUT:** The Cart or Checkout.                    |
| metadata.logic            | The type of recommendation banner which was configured in the KMC. This will be one of:&#xA;TRENDING&#xA;TRENDING\_PERSONALIZED&#xA;NEWEST\_ARRIVALS&#xA;RECENTLY\_VIEWED&#xA;HAND\_PICKED&#xA;OTHER\_ALSO\_VIEWED&#xA;SIMILAR&#xA;BOUGHT\_TOGETHER |
| metadata.maxProducts      | The maximum number of products to show within this banner.                                                                                                                                                                                          |
| metadata.productThreshold | The minimum number of results before this banner will be displayed.                                                                                                                                                                                 |
| metadata.enabled          | Whether or not this particular banner is enabled.                                                                                                                                                                                                   |
| search.basePath           | The search URL to be used to send the Recommendation request to, eg. eucs19v2.ksearchnet.com/cs/v2/search.                                                                                                                                          |
| search.payload            | This correlates to the recordQueries section of the API call to be fired for this Recommendation.                                                                                                                                                   |
| templates.base            | The HTML to be used for rendering the Recommendation banner, in Klevu JavaScript Library markup.                                                                                                                                                    |
| styles.base               | The CSS that is used for rendering the Recommendation banner, in Klevu's Template JS Library markup.                                                                                                                                                |
| scripts.recsObject        | The Javascript that is executed after the rendering of the HTML Recommendation banner, in Klevu's Template JS Library markup.                                                                                                                       |

**Note regarding the response:**

*templates.base*, *styles.base*, and *scripts.recsObject&#x20;*&#x72;eturned in the configuration API response should not be used when using the API directly since they require the Klevu's Template JS Library.

[title] Overview
[path] Guide/MOI/

# Prerequisites

- You must have a valid Klevu API Key for each store that you want to set up MOI for. The API key can be obtained by registering an account with Klevu.
- MOI as an add-on must be enabled for the respective API key. Please reach out to the Klevu [support team](https://help.klevu.com/support/tickets/new) to setup & activate MOI.

#

# Endpoints

### Posting a conversation

All requests must be sent to the following endpoint as POST requests. The body submitted must be a valid Json payload.

**POST** [https://moi-ai.ksearchnet.com/chat/send](https://moi-ai.ksearchnet.com/chat/send)

### Posting a feedback

Any conversation specific feedback must be sent to the following endpoint as POST requests. The body submitted must be a valid JSON payload.

**POST** [https://moi-ai.ksearchnet.com/chat/feedback](https://moi-ai.ksearchnet.com/chat/feedback)  

#

# UI Elements

Before we get into understanding API, let us review the different UI elements and what we call them. Throughout the documentation, you will see suggestions on what bits of request/response to use for what UI elements.

![](https://lh7-us.googleusercontent.com/ilda3AJMiioZnpieu6PDc92utvX__CrPBIz98Gzt8j86ga1C2nLKaZm2JKhAvLTlz6uU31AaAr09U4oz8zQFiKc7ruP6tNShNKBcWhncmhsKPQic4KPMhk41rT6Nw39XiQqP8X1qfj6AJ-LwtUIMS70)


[title] Configurations
[path] Guide/Smart Search/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

There are numerous settings, preferences, and configurations available with APIv2 to fine-tune your search and category merchandising queries. This section explores them in more detail.&#x20;

## Sorting

The default sorting of results is RELEVANCE, which uses Klevu A.I. to determine the order. There are various other options available which you can provide to your customers as required.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Sort",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "RELEVANCE",
        "type": "String",
        "description": "This is the default sort order, which uses a combination of Klevu A.I. and your own merchandising configuration to determine the order of the results. "
      },
      {
        "kind": "optional",
        "name": "PRICE_ASC",
        "type": "string",
        "description": "Sort the results in ascending order by the salePrice value of each record."
      },
      {
        "kind": "optional",
        "name": "PRICE_DESC",
        "type": "string",
        "description": "Sort the results in descending order by the salePrice value of each record."
      },
      {
        "kind": "optional",
        "name": "NAME_ASC",
        "type": "string",
        "description": "Sort the results in ascending by the name of each record, in alphabetical order."
      },
      {
        "kind": "optional",
        "name": "NAME_DESC",
        "type": "string",
        "description": "Sort the results in descending by the name of each record, in alphabetical order."
      },
      {
        "kind": "optional",
        "name": "RATING_ASC",
        "type": "string",
        "description": "Sort the results in ascending by each record's average rating, if this data has been indexed in your store."
      },
      {
        "kind": "optional",
        "name": "RATING_DESC",
        "type": "string",
        "description": "Sort the results in descending by each record's average rating, if this data has been indexed in your store."
      },
      {
        "kind": "optional",
        "name": "NEW_ARRIVAL_ASC",
        "type": "string",
        "description": "Sort your records in ascending order based on their published date. "
      },
      {
        "kind": "optional",
        "name": "NEW_ARRIVAL_DESC",
        "type": "string",
        "description": "Sort your records in descending order based on their published date. "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 18,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 17,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 105,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"score\": \"0.19684093\",\n                    \"salePrice\": \"24.00\",\n                    \"name\": \"Aero Daily Fitness Tee\",\n                    \"id\": \"31366478200894\"\n                },\n                {\n                    \"score\": \"0.19684093\",\n                    \"salePrice\": \"24.00\",\n                    \"name\": \"Aero Daily Fitness Tee\",\n                    \"id\": \"31366478364734\"\n                },\n                {\n                    \"score\": \"0.19684093\",\n                    \"salePrice\": \"24.00\",\n                    \"name\": \"Aero Daily Fitness Tee\",\n                    \"id\": \"31366478495806\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"40.00\",\n                    \"name\": \"Ana Running Short\",\n                    \"id\": \"31366431768638\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"40.00\",\n                    \"name\": \"Ana Running Short\",\n                    \"id\": \"31366431899710\"\n                },\n                {\n                    \"score\": \"1.0985984\",\n                    \"salePrice\": \"40.00\",\n                    \"name\": \"Ana Running Short\",\n                    \"id\": \"31366431834174\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"42.00\",\n                    \"name\": \"Angel Light Running Short\",\n                    \"id\": \"31366434062398\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"42.00\",\n                    \"name\": \"Angel Light Running Short\",\n                    \"id\": \"31366433177662\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"42.00\",\n                    \"name\": \"Angel Light Running Short\",\n                    \"id\": \"31366433996862\"\n                },\n                {\n                    \"score\": \"1.0985929\",\n                    \"salePrice\": \"32.50\",\n                    \"name\": \"Apollo Running Short\",\n                    \"id\": \"31366465880126\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"20.00\",\n                    \"name\": \"Arcadio Gym Short\",\n                    \"id\": \"31366462668862\"\n                },\n                {\n                    \"score\": \"1.0985985\",\n                    \"salePrice\": \"20.00\",\n                    \"name\": \"Arcadio Gym Short\",\n                    \"id\": \"31366462767166\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"sort\": \"NAME_ASC\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"rating\",\n          \"salePrice\",\n          \"score\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"sort\": \"NAME_ASC\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"rating\",\n          \"salePrice\",\n          \"score\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"sort\":\"NAME_ASC\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"rating\",\"salePrice\",\"score\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"sort\\\": \\\"NAME_ASC\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"rating\\\",\\n          \\\"salePrice\\\",\\n          \\\"score\\\"\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"sort\":\"NAME_ASC\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"rating\",\"salePrice\",\"score\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to set record sorting order. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "sort",
  "legacyHash": "CcPLwsroBJn8JRJLHZ2ot"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=sorting&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Pagination&#x20;

You may wish to split larger result sets over multiple pages. You can do this using pagination. Simply specify a page size for how many results each page should include, and an offset of which record to start each result set from.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Pagination",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "limit",
        "type": "Integer",
        "description": "Specify the number of records you would like to display per page. If this field is not passed in the API, the default value is 12. You can fetch a maximum of 100 records when you pass the limit. In order to get more than 100 records, you must define the 'fields' in the API."
      },
      {
        "kind": "optional",
        "name": "offset",
        "type": "Integer",
        "description": "Specify the index at which to start counting the number of results from.\n\nThe index of the first record in a result set is 0. Thus, if you want to start from the 6th result, use an offset of 5."
      },
      {
        "kind": "optional",
        "name": "typeOfSearch",
        "type": "string",
        "description": "After the first has been retrieved, for subsequent pagination requests it is recommended to include the typeOfSearch value using the same value that came back in the meta data with the results of the first result. This will give a performance benefit since Klevu does not need to try different search types, and will also assure consistency of results across pages."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 12,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 11,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 105,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 4,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465060926\"\n                },\n                {\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462472254\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465191998\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465126462\"\n                },\n                {\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462439486\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"limit\": 5,\n        \"offset\": 4,\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"limit\": 5,\n        \"offset\": 4,\n        \"typeOfSearch\": \"WILDCARD_AND\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"limit\":5,\"offset\":4,\"typeOfSearch\":\"WILDCARD_AND\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"limit\\\": 5,\\n        \\\"offset\\\": 4,\\n        \\\"typeOfSearch\\\": \\\"WILDCARD_AND\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"limit\":5,\"offset\":4,\"typeOfSearch\":\"WILDCARD_AND\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to paginate records. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "pagination-1",
  "legacyHash": "kFUu5Gv3MJQdKVqAqy7PY"
}
```
:::

**Understanding response format**

| **Params**        | **Description**                                                    |   |
| ----------------- | ------------------------------------------------------------------ | - |
| noOfResults       | The number of results requested to be returned for this query.     |   |
| totalResultsFound | The total number of results found for this query.                  |   |
| offset            | The index of the first result returned in this response.           |   |
| typeOfSearch      | The query type that was executed by Klevu to retrieve the results. |   |

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=pagination&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Fields

By default, Klevu will return most of the data available in a record. If you only need certain elements and want to keep the response size small for performance reasons, you can specify only the fields you are interested in.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Fields",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "fields",
        "type": "Array",
        "description": "An array of the attribute IDs that you wish to retrieve, eg. \"id\", \"name\", \"salePrice\", etc. Please refer to Searching for Records to see all of the available fields."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 14,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 12,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 105,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"salePrice\": \"45.00\",\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431146046\"\n                },\n                {\n                    \"salePrice\": \"45.00\",\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431080510\"\n                },\n                {\n                    \"salePrice\": \"45.00\",\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431014974\"\n                },\n                {\n                    \"salePrice\": \"32.50\",\n                    \"name\": \"Meteor Workout Short\",\n                    \"id\": \"31366465781822\"\n                },\n                {\n                    \"salePrice\": \"29.00\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465060926\"\n                },\n                {\n                    \"salePrice\": \"27.00\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462472254\"\n                },\n                {\n                    \"salePrice\": \"29.00\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465191998\"\n                },\n                {\n                    \"salePrice\": \"29.00\",\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465126462\"\n                },\n                {\n                    \"salePrice\": \"27.00\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462439486\"\n                },\n                {\n                    \"salePrice\": \"27.00\",\n                    \"name\": \"Pierce Gym Short\",\n                    \"id\": \"31366462373950\"\n                },\n                {\n                    \"salePrice\": \"32.00\",\n                    \"name\": \"Sol Active Short\",\n                    \"id\": \"31366463094846\"\n                },\n                {\n                    \"salePrice\": \"32.00\",\n                    \"name\": \"Sol Active Short\",\n                    \"id\": \"31366463029310\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"salePrice\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        }\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"salePrice\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        }\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"fields\":[\"id\",\"name\",\"salePrice\"],\"query\":{\"term\":\"short\"}},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"salePrice\\\"\\n        ],\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        }\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"fields\":[\"id\",\"name\",\"salePrice\"],\"query\":{\"term\":\"short\"}},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to limit fields/attributes in search response. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "fields-1",
  "legacyHash": "4Ikpba26FPvecDAjnnyZV"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=fields&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Grouping

The groupBy parameter takes the name of a field indexed in the Klevu Search backend and ensures that there is only one record for each unique value of this field in the search results.

By default, the groupBy operation is performed on the itemGroupId field. When querying for KLEVU\_CATEGORY or KLEVU\_CMS records, it is recommended to use name as the groupBy parameter value.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Grouping Results",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "groupBy",
        "type": "String",
        "description": "The key of the attribute to group by, for example 'name'. Currently the only supported values are id and name."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 19,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 17,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 1,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"Adrienne Trek Jacket\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Adrienne Trek Jacket\",\n                    \"id\": \"31366454378558\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"groupBy\": \"name\",\n        \"query\": {\n          \"term\": \"Adrienne Trek Jacket\"\n        },\n        \"sort\": \"NAME_ASC\",\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"groupBy\": \"name\",\n        \"query\": {\n          \"term\": \"Adrienne Trek Jacket\"\n        },\n        \"sort\": \"NAME_ASC\",\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"groupBy\":\"name\",\"query\":{\"term\":\"Adrienne Trek Jacket\"},\"sort\":\"NAME_ASC\",\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"groupBy\\\": \\\"name\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"Adrienne Trek Jacket\\\"\\n        },\\n        \\\"sort\\\": \\\"NAME_ASC\\\",\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"groupBy\":\"name\",\"query\":{\"term\":\"Adrienne Trek Jacket\"},\"sort\":\"NAME_ASC\",\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to group search results.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "grouping-results",
  "legacyHash": "TQ2sjLiscJsKR2KDAZyGr"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=grouping&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Type of search

The typeOfSearch parameter defines the behaviour when identifying matches for a searched term. For example, whether all or just one of the entered words must be matched, whether to allow spelling mistakes, etc.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Type of search",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "DEFAULT",
        "type": "String",
        "description": "When this value is specified, Klevu will go through a number of attempts to find matching records. The first type attempted is AND. If there aren't any results found, Klevu tries to find products with the FUZZY_AND query type.\n\nAs long as no matches are found, Klevu will continue to fire different query types in the following order:\n\nAND\nFUZZY_AND\nWILDCARD_AND\nFUZZY_WILDCARD_AND\nWILDCARD_OR\nFUZZY_OR\n\nNote that when a search term only contains a single word or more than six words, the 'OR' query types will be skipped.",
        "": "When this value is specified, Klevu will go through a number of attempts to find matching records. The first type attempted is AND. If there aren't any results found, Klevu tries to find products with the FUZZY_AND query type.\n\nAs long as no matches are found, Klevu will continue to fire different query types in the following order:\n\nAND\nFUZZY_AND\nWILDCARD_AND\nFUZZY_WILDCARD_AND\nWILDCARD_OR\nFUZZY_OR\n\nNote that when a search term only contains a single word or more than six words, the 'OR' query types will be skipped."
      },
      {
        "kind": "optional",
        "name": "AND",
        "type": "string",
        "description": "All of the exact words of a query must be found in a record for it to be included in the results. No fuzziness or wildcards are included.\n\nFor example, a search for \"hooded jacket\" will only return records that contain the exact terms \"hooded\" AND \"jacket\".",
        "": "All of the exact words of a query must be found in a record for it to be included in the results. No fuzziness or wildcards are included.\n\nFor example, a search for \"hooded jacket\" will only return records that contain the exact terms \"hooded\" AND \"jacket\"."
      },
      {
        "name": "FUZZY_AND",
        "kind": "optional",
        "type": "string",
        "description": "This is the same as a AND query, however a certain amount of 'fuzziness' is allowed to account for spelling mistakes.\n\nFor example, if the searched query contains spelling mistakes like \"hooder jakcet\", Klevu will still be able to match any records containing the words \"hooded\" AND \"jacket\".",
        "": "This is the same as a AND query, however a certain amount of 'fuzziness' is allowed to account for spelling mistakes.\n\nFor example, if the searched query contains spelling mistakes like \"hooder jakcet\", Klevu will still be able to match any records containing the words \"hooded\" AND \"jacket\"."
      },
      {
        "kind": "optional",
        "name": "WILDCARD_AND",
        "type": "string",
        "description": "This is an 'AND' query, so all words of the query must be found somewhere in a record for it to be included in the results. The last word of the query will have a wildcard suffix appended.\n\nFor example, if the searched query is \"hooded jacket\", this will become \"hooded jacket*\", i.e., Klevu will try to find records containing the word \"hooded\" AND any words beginning with \"jacket\".",
        "": "optional"
      },
      {
        "kind": "optional",
        "name": "FUZZY_WILDCARD_AND",
        "type": "string",
        "description": "This is the same as a WILDCARD_AND query, however a certain amount of 'fuzziness' is allowed to account for spelling mistakes.\n\nFor example, if the searched query contains spelling mistakes like \"hooder jakcet\", Klevu will still be able to match any records containing the words \"hooded\" AND \"jacket\".",
        "": "FUZZY_WILDCARD_AND"
      },
      {
        "kind": "optional",
        "name": "WILDCARD_OR",
        "type": "string",
        "description": "This is an 'OR' query so at least one of the words in the query must be found somewhere in a record for it to be included in the results. The last word of the query will have a wildcard suffix appended.\n\nFor example, if the searched query is \"hooded jacket\", this will become \"hooded jacket*\", ie. Klevu will try to find records containing the word \"hooded\" OR any words beginning with \"jacket\"."
      },
      {
        "kind": "optional",
        "name": "FUZZY_OR",
        "type": "string",
        "description": "This is the same as a WILDCARD_OR query, however a certain amount of 'fuzziness' is allowed to account for spelling mistakes.\n\nFor example, if the searched query contains spelling mistakes like \"hooder jakcet\", Klevu will still be able to match any records containing the words \"hooded\" OR \"jacket\"."
      },
      {
        "kind": "optional",
        "name": "OR",
        "type": "string",
        "description": "At least one exact word of a query must be found in a record for it to be included in a results. No fuzziness or wildcards are included.\n\nFor example a search for \"hooded jacket\" will only return records which contain one of the exact terms \"hooded\" OR \"jacket\"."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 17,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 16,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 190,\n                \"typeOfSearch\": \"FUZZY_OR\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Rapha Sports Short\",\n                    \"id\": \"31366464503870\"\n                },\n                {\n                    \"name\": \"Rapha Sports Short\",\n                    \"id\": \"31366464110654\"\n                },\n                {\n                    \"name\": \"Rapha Sports Short\",\n                    \"id\": \"31366464667710\"\n                },\n                {\n                    \"name\": \"Shorts\",\n                    \"id\": \"category_156703227966\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431146046\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431014974\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431080510\"\n                },\n                {\n                    \"name\": \"Meteor Workout Short\",\n                    \"id\": \"31366465781822\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465126462\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465191998\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465060926\"\n                },\n                {\n                    \"name\": \"Bess Yoga Short\",\n                    \"id\": \"31366434226238\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"typeOfSearch\": \"FUZZY_OR\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"typeOfSearch\": \"FUZZY_OR\",\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"typeOfSearch\":\"FUZZY_OR\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"typeOfSearch\\\": \\\"FUZZY_OR\\\",\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"typeOfSearch\":\"FUZZY_OR\",\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\"]},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to change type of search results.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "type-of-search-1",
  "legacyHash": "AFKlUX4AbBKCZLN7QCBp8"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=typeOfSearch&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Preferences

There are a number of preferences available for fine-tuning your queries. For example, you can control whether or not to allow *fuzzy search* for spelling mistakes on a query by query basis. The available **searchPrefs** are detailed below.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Search preferences",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "showOutOfStockProducts",
        "type": "String",
        "description": "Whether or not your store should include 'Out of Stock' products in search results by default can be configured within the Klevu Merchant Centre. However, if you would like to override this for a particular query, please include one of these flags."
      },
      {
        "kind": "optional",
        "name": "hideOutOfStockProducts",
        "type": "string",
        "description": "Flag to hide out-of-stock products.\n\n"
      },
      {
        "kind": "optional",
        "name": "disableStockSorting",
        "type": "string",
        "description": "This can be used in conjunction with showOutOfStockProducts. If your store is configured to display out of stock products, they will be displayed at the very end of the search results after all in stock products have been displayed. By using this flag you can disable this logic, and cause all products to be ranked in an order that disregards their stock status."
      },
      {
        "kind": "optional",
        "name": "includeStopwords",
        "type": "string",
        "description": "By default, functional words such as prepositions, pronouns, articles, etc. are excluded from searches. Add this flag to include these stopwords in your search."
      },
      {
        "kind": "optional",
        "name": "excludeIds",
        "type": "string",
        "description": "Use this flag to disable the searching of record IDs."
      },
      {
        "kind": "optional",
        "name": "includeDescription",
        "type": "string",
        "description": "Whether or not a record's 'description' is considered for search results can be configured by Klevu Support on a store-by-store basis, however if you would like to override this for a particular query, please include one of these flags."
      },
      {
        "kind": "optional",
        "name": "excludeDescription",
        "type": "string",
        "description": "Use this flag to exclude search in the description."
      },
      {
        "kind": "optional",
        "name": "disableFuzzyMatch",
        "type": "string",
        "description": "This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to disable the FUZZY_AND and FUZZY_OR search types from being attempted."
      },
      {
        "kind": "optional",
        "name": "disableWildcard",
        "type": "string",
        "description": "This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to disable the WILDCARD_AND and WILDCARD_OR search types from being attempted."
      },
      {
        "kind": "optional",
        "name": "disableORSearch",
        "type": "string",
        "description": "This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to disable the WILDCARD_OR and FUZZY_OR search types from being attempted."
      },
      {
        "kind": "optional",
        "name": "partialMatch",
        "type": "string",
        "description": "Enable partial match for the last word of a query, where the last word searched can be a substring of any other word found in a record. This can be useful for non-English languages.\n\nFor example let's say a product has the name \"rödvinsglas\" (red wine glass). If searching for \"högt glas\" (tall glass) it may not match since the record has no words starting with 'glas'. By providing this flag, the search would become \"högt *glas*\" meaning it would match the record since it contains a word which ends with 'glas'."
      },
      {
        "kind": "optional",
        "name": "partialMatchForAllWords",
        "type": "string",
        "description": "Similar to partialMatch, but for all words rather than just the last. In the same \"rödvinsglas\" example, a search for \"högt glas\" would become \"*högt* *glas*\", so any records containing words containing 'högt' or 'glas' would result in a match."
      },
      {
        "kind": "optional",
        "name": "disableWordShingles",
        "type": "string",
        "description": "For a query longer than one word, all the possible bigrams and trigrams (i.e. formed out of query terms) are looked up in records and the ones having one or more of them are boosted higher up in the search results. You can use this flag to disable such boosting."
      },
      {
        "kind": "optional",
        "name": "searchCompoundsAsAndQuery",
        "type": "string",
        "description": "When a compound word is searched for, i.e. two or more individual words joined together as one word, Klevu automatically disjoints them if the de-compounding feature is enabled for your store.\n\nFor example, a search for \"fairylights\" would be treated as \"fairy lights\", but with the added condition that those words must appear within 5 words of each other in a matching record.\n\nIf you would prefer that the words \"fairy\" and \"light\" could be found anywhere within the record, not necessarily near one another, then please include this flag."
      },
      {
        "kind": "optional",
        "name": "enableBoostingOriginalTermsInSynonyms",
        "type": "string",
        "description": "By default, synonyms are treated equally to their query term. Should you wish to give higher priority to the actual terms your customer entered in the query over their synonyms, please include this flag in your search preferences."
      },
      {
        "kind": "optional",
        "name": "showDisabledFacets",
        "type": "string",
        "description": "It is possible to configure which facets or filters should be enabled or disabled within the Klevu Merchant Centre. By including this flag, all facets will be returned regardless of whether they have been disabled in the KMC."
      },
      {
        "kind": "optional",
        "name": "showFiltersWithSmallCount",
        "type": "string",
        "description": "By default some filters are excluded from the results if they only have a small number of results. Please use this flag to override this logic and include all filters in the response."
      },
      {
        "kind": "optional",
        "name": "includeCategoryFilterInCatNav",
        "type": "string",
        "description": "When the typeOfRequest is 'CATNAV', the filter for 'Category' is automatically excluded since you are already within the context of a category. Use this flag to override this logic and return the category filters even for CatNav requests."
      },
      {
        "kind": "optional",
        "name": "enableScores",
        "type": "string",
        "description": "include the score information with the response fields: klevu_product_boosting and klevu_manual_boosting."
      },
      {
        "kind": "optional",
        "name": "disableGrouping",
        "type": "string",
        "description": "By default, Klevu groups results by itemGroupId. Use this flag to disable the grouping of products.\n"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n   meta: {\n      qTime: 29,\n      responseCode: 200\n   },\n   queryResults: [\n      {\n         id: \"productSearch\",\n         meta: {\n            qTime: 26,\n            noOfResults: 12,\n            totalResultsFound: 108,\n            typeOfSearch: \"WILDCARD_AND\",\n            offset: 0,\n            debuggingInformation: {},\n            notificationCode: 1,\n            searchedTerm: \"short\",\n            apiKey: \"klevu-156925593843210765\",\n            isPersonalised: false\n         },\n         records: [\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384016203838\",\n               score: \"1.7803618\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"45.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366431014974\",\n               imageHover: \"\",\n               sku: \"WSH12-28-Red\",\n               brand: \"KSD\",\n               basePrice: \"45.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-red_main_9999e03f-694d-4f0c-83ab-8c0200029275_medium.jpg?v=1575477719\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"45.0\",\n               klevu_product_boosting: \"1.2\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-red\",\n               tags: \"body-hugging, nylon, Red, Running, Short\",\n               size: \"Medium\",\n               name: \"Erika Running Short\",\n               shortDesc: \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384016269374\",\n               score: \"1.7803618\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"45.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366431080510\",\n               imageHover: \"\",\n               sku: \"WSH12-28-Purple\",\n               brand: \"KSD\",\n               basePrice: \"45.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-purple_main_c57ce41e-7b0e-4cd2-a0de-18ddb6d2017a_medium.jpg?v=1575477720\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"45.0\",\n               klevu_product_boosting: \"1.2\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-purple\",\n               tags: \"body-hugging, nylon, Red, Running, Short\",\n               size: \"Large\",\n               name: \"Erika Running Short\",\n               shortDesc: \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384016334910\",\n               score: \"1.7803618\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"45.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366431146046\",\n               imageHover: \"\",\n               sku: \"WSH12-28-Green\",\n               brand: \"KSD\",\n               basePrice: \"45.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wsh12-green_main_3ac6ebe5-2c3e-45cf-91cf-ec54de5e5e3a_medium.jpg?v=1575477721\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"45.0\",\n               klevu_product_boosting: \"1.2\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/erika-running-short-green\",\n               tags: \"body-hugging, Green, nylon, Running, Short\",\n               size: \"Small\",\n               name: \"Erika Running Short\",\n               shortDesc: \"A great short with a body-hugging design, the Erika Running Short is perfect for runners who prefer a fitted short rather than the traditional baggy variety. • Seafoam pattern running shorts. • Elastic waistband. • Snug fit. • 4''\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384040386622\",\n               score: \"1.513042\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"32.50\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366465781822\",\n               imageHover: \"\",\n               sku: \"MSH03-32-Black\",\n               brand: \"KKE\",\n               basePrice: \"32.5\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh03-black_main_a8796b84-9c70-4146-9c73-2295b0d260a7_medium.jpg?v=1575478122\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"32.5\",\n               klevu_product_boosting: \"1.02\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/meteor-workout-short-black\",\n               tags: \"black, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Small\",\n               name: \"Meteor Workout Short\",\n               shortDesc: \"Step into the Meteor Workout Short for an incredibly lightweight fitness experience. Its breathable construction and an inner brief provide additional comfort and support, while the adjustable waistband offers the perfect fit to take you to the fi\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384039796798\",\n               score: \"1.4835187\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"29.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-black_main_f61ee526-b9d3-4eaa-b7b2-80dc400f31b0_medium.jpg?v=1575478115\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366465191998\",\n               imageHover: \"\",\n               sku: \"MSH05-32-Black\",\n               brand: \"KKE\",\n               basePrice: \"29.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-black_main_f61ee526-b9d3-4eaa-b7b2-80dc400f31b0_medium.jpg?v=1575478115\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"29.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-black\",\n               tags: \"Black, Machine, motion-friendly, Nylon, Relaxed fit, Smooth, Summer, yoga-short\",\n               size: \"Small\",\n               name: \"Hawkeye Yoga Short\",\n               shortDesc: \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384039665726\",\n               score: \"1.4835187\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"29.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366465060926\",\n               imageHover: \"\",\n               sku: \"MSH05-32-Gray\",\n               brand: \"KSD\",\n               basePrice: \"29.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-gray_main_0f869cff-09fb-403a-a209-cf092f4d3c1a_medium.jpg?v=1575478112\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"29.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-gray\",\n               tags: \"Gray, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Medium\",\n               name: \"Hawkeye Yoga Short\",\n               shortDesc: \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384039731262\",\n               score: \"1.4835187\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"29.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-blue_main_2130114d-06b0-4793-8fc2-bf77411297e4_medium.jpg?v=1575478114\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366465126462\",\n               imageHover: \"\",\n               sku: \"MSH05-32-Blue\",\n               brand: \"MNH\",\n               basePrice: \"29.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh05-blue_main_2130114d-06b0-4793-8fc2-bf77411297e4_medium.jpg?v=1575478114\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"29.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/hawkeye-yoga-short-blue\",\n               tags: \"Blue, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Large\",\n               name: \"Hawkeye Yoga Short\",\n               shortDesc: \"What more do you need than a sporty yoga short made with organic cotton and a little spandex for mobility? The Hawkeye Yoga Short brings a stylish, standard fit you can sport with confidence outside the studio. • Dark gray shorts with red a\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384037765182\",\n               score: \"1.4835187\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"27.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-gray_main_4bb28c53-a928-47a0-92ea-ecd303f97dba_medium.jpg?v=1575478089\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366462439486\",\n               imageHover: \"\",\n               sku: \"MSH12-32-Gray\",\n               brand: \"MNH\",\n               basePrice: \"27.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-gray_main_4bb28c53-a928-47a0-92ea-ecd303f97dba_medium.jpg?v=1575478089\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"27.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-gray\",\n               tags: \"Gray, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Large\",\n               name: \"Pierce Gym Short\",\n               shortDesc: \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384037830718\",\n               score: \"1.4835187\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"27.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-black_main_2ef78733-04a5-4345-9f5f-992d0cfffe8d_medium.jpg?v=1575478090\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366462472254\",\n               imageHover: \"\",\n               sku: \"MSH12-32-Black\",\n               brand: \"KKE\",\n               basePrice: \"27.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-black_main_2ef78733-04a5-4345-9f5f-992d0cfffe8d_medium.jpg?v=1575478090\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"27.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-black\",\n               tags: \"Black, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Small\",\n               name: \"Pierce Gym Short\",\n               shortDesc: \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384037699646\",\n               score: \"1.4835186\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"27.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-red_main_6c29f610-d5f7-4e1a-bde4-1fb148964be5_medium.jpg?v=1575478088\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366462373950\",\n               imageHover: \"\",\n               sku: \"MSH12-32-Red\",\n               brand: \"KSD\",\n               basePrice: \"27.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh12-red_main_6c29f610-d5f7-4e1a-bde4-1fb148964be5_medium.jpg?v=1575478088\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"27.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/pierce-gym-short-red\",\n               tags: \"Cotton, Machine, Relaxed fit, Res, Short, Summer\",\n               size: \"Medium\",\n               name: \"Pierce Gym Short\",\n               shortDesc: \"The Pierce Gym Short is similar to our Arcadio Gym Short, but designed with a fitted, tapered look. A flat waistband with an adjustable drawstring adds comfort, with zippered pockets for safe, easy storage. • Dark red cotton shorts. • 8\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384038256702\",\n               score: \"1.4835119\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"32.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-green_main_18d664f2-5ba2-421d-b89a-87cb73d86416_medium.jpg?v=1575478095\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366463029310\",\n               imageHover: \"\",\n               sku: \"MSH10-32-Green\",\n               brand: \"MNH\",\n               basePrice: \"32.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-green_main_18d664f2-5ba2-421d-b89a-87cb73d86416_medium.jpg?v=1575478095\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"32.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/sol-active-short-green\",\n               tags: \"Green, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Large\",\n               name: \"Sol Active Short\",\n               shortDesc: \"You'll let your fear go and push your limits in your new Sol Active Short. Featuring ultra-breathable performance fabric and a flat comfort-fit waistband, the Sol Active Short is perfect for high-intensity circuits or high-heat bikram. • Li\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            },\n            {\n               discount: \"\",\n               hideGroupPrices: \"\",\n               type: \"Shorts\",\n               itemGroupId: \"4384038158398\",\n               score: \"1.4835119\",\n               freeShipping: \"\",\n               storeBaseCurrency: \"GBP\",\n               price: \"32.00\",\n               toPrice: \"\",\n               imageUrl: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-purple_main_1e2fd886-6ce1-4258-8fe5-6ca863ab5f9e_medium.jpg?v=1575478094\",\n               currency: \"GBP\",\n               inStock: \"yes\",\n               id: \"31366462931006\",\n               imageHover: \"\",\n               sku: \"MSH10-32-Purple\",\n               brand: \"KSD\",\n               basePrice: \"32.0\",\n               startPrice: \"\",\n               image: \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/msh10-purple_main_1e2fd886-6ce1-4258-8fe5-6ca863ab5f9e_medium.jpg?v=1575478094\",\n               deliveryInfo: \"\",\n               hideAddToCart: \"\",\n               salePrice: \"32.0\",\n               klevu_product_boosting: \"1.0\",\n               swatchesInfo: \"\",\n               weight: \"\",\n               klevu_category: \"KLEVU_PRODUCT;Products;;Shorts  @ku@kuCategory@ku@\",\n               totalVariants: 0,\n               groupPrices: \"\",\n               url: \"https://jsv2-shopify-demo.ksearchmisc.com/products/sol-active-short-purple\",\n               tags: \"Black, Machine, Nylon, Relaxed fit, Short, Summer\",\n               size: \"Medium\",\n               name: \"Sol Active Short\",\n               shortDesc: \"You'll let your fear go and push your limits in your new Sol Active Short. Featuring ultra-breathable performance fabric and a flat comfort-fit waistband, the Sol Active Short is perfect for high-intensity circuits or high-heat bikram. • Li\",\n               klevu_manual_boosting: \"1.0\",\n               category: \"Shorts\"\n            }\n         ],\n         filters: []\n      }\n   ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"searchPrefs\": [\n          \"showOutOfStockProducts\",\n          \"disableStockSorting\",\n          \"includeStopwords\",\n          \"excludeIds\",\n          \"includeDescription\",\n          \"disableFuzzyMatch\",\n          \"disableWildcard\",\n          \"disableORSearch\",\n          \"partialMatch\",\n          \"partialMatchForAllWords\",\n          \"disableWordShingles\",\n          \"searchCompoundsAsAndQuery\",\n          \"enableBoostingOriginalTermsInSynonyms\",\n          \"showDisabledFacets\",\n          \"showFiltersWithSmallCount\",\n          \"includeCategoryFilterInCatNav\",\n          \"enableScores\",\n          \"disableGrouping\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        }\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"searchPrefs\": [\n          \"showOutOfStockProducts\",\n          \"disableStockSorting\",\n          \"includeStopwords\",\n          \"excludeIds\",\n          \"includeDescription\",\n          \"disableFuzzyMatch\",\n          \"disableWildcard\",\n          \"disableORSearch\",\n          \"partialMatch\",\n          \"partialMatchForAllWords\",\n          \"disableWordShingles\",\n          \"searchCompoundsAsAndQuery\",\n          \"enableBoostingOriginalTermsInSynonyms\",\n          \"showDisabledFacets\",\n          \"showFiltersWithSmallCount\",\n          \"includeCategoryFilterInCatNav\",\n          \"enableScores\",\n          \"debugQuery\",\n          \"disableGrouping\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        }\n      },\n      \"id\": \"productSearch\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"searchPrefs\":[\"showOutOfStockProducts\",\"disableStockSorting\",\"includeStopwords\",\"excludeIds\",\"includeDescription\",\"disableFuzzyMatch\",\"disableWildcard\",\"disableORSearch\",\"partialMatch\",\"partialMatchForAllWords\",\"disableWordShingles\",\"searchCompoundsAsAndQuery\",\"enableBoostingOriginalTermsInSynonyms\",\"showDisabledFacets\",\"showFiltersWithSmallCount\",\"includeCategoryFilterInCatNav\",\"enableScores\",\"debugQuery\",\"disableGrouping\"],\"query\":{\"term\":\"short\"}},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"searchPrefs\\\": [\\n          \\\"showOutOfStockProducts\\\",\\n          \\\"disableStockSorting\\\",\\n          \\\"includeStopwords\\\",\\n          \\\"excludeIds\\\",\\n          \\\"includeDescription\\\",\\n          \\\"disableFuzzyMatch\\\",\\n          \\\"disableWildcard\\\",\\n          \\\"disableORSearch\\\",\\n          \\\"partialMatch\\\",\\n          \\\"partialMatchForAllWords\\\",\\n          \\\"disableWordShingles\\\",\\n          \\\"searchCompoundsAsAndQuery\\\",\\n          \\\"enableBoostingOriginalTermsInSynonyms\\\",\\n          \\\"showDisabledFacets\\\",\\n          \\\"showFiltersWithSmallCount\\\",\\n          \\\"includeCategoryFilterInCatNav\\\",\\n          \\\"enableScores\\\",\\n          \\\"debugQuery\\\",\\n          \\\"disableGrouping\\\"\\n        ],\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        }\\n      },\\n      \\\"id\\\": \\\"productSearch\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"searchPrefs\":[\"showOutOfStockProducts\",\"disableStockSorting\",\"includeStopwords\",\"excludeIds\",\"includeDescription\",\"disableFuzzyMatch\",\"disableWildcard\",\"disableORSearch\",\"partialMatch\",\"partialMatchForAllWords\",\"disableWordShingles\",\"searchCompoundsAsAndQuery\",\"enableBoostingOriginalTermsInSynonyms\",\"showDisabledFacets\",\"showFiltersWithSmallCount\",\"includeCategoryFilterInCatNav\",\"enableScores\",\"debugQuery\",\"disableGrouping\"],\"query\":{\"term\":\"short\"}},\"id\":\"productSearch\"}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to use different search preferences. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "search-preferences",
  "legacyHash": "H8JzOsaZN1VAbxjcEZOmj"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=preferences&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::





[title] Introduction
[path] /

At Klevu, we believe that every integration is unique. To build an awesome product discovery experience, Klevu offers open APIs, SDKs, and platform plugins/apps. Depending on the business requirements, one can explore the available solutions and build a personalized online experience.&#x20;

If you are a **developer** looking forward to exploring our APIs, please follow the steps below to get started:&#x20;

- [Sign-up](https://box.klevu.com/merchant/signup) for a Klevu account.
- Indexing your own catalog using one of the below methods:
  - Klevu has developed native plugins/extensions to ease the integrations. If your requirement allows, we strongly recommend using one of our available [plugins/apps](https://help.klevu.com/support/solutions/5000174073). &#x20;
  - For the platforms where Klevu does not offer native plugins/apps, one can use the [product feed](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) to submit the catalog.&#x20;
  - If you are having custom requirements for indexing and would like to take full control of data updates, you may want to use our REST-ful [Data Indexing](https://docs.klevu.com/indexing-apis) APIs.
- Build your own product discovery experience using one of the below methods:&#x20;
  - If you have already installed one of [plugins/apps](https://help.klevu.com/support/solutions/5000174073), by default, the installation configures Klevu Template JS. Learn more about Template JS by going through [Introduction](docId:2QdXpH6Pj2hflC-JyORbA). &#x20;
  - For headless commerce, you may want to explore our headless library by going through  [Introduction](docId\:Ll504VM4E5pZHuiE_r-bR).  This library already covers instructions for React, Vue, and Angular.&#x20;
  - For server-side API implementation, explore our open product discovery APIs [Smart Search](docId:9eYi1-ZiJWXh97ceQzRPe)  [Smart Category Merchandising](docId\:kRpW4ReRXWjO660KkaMNH) and [Smart Recommendations](docId:4LOFui8shVdj88SWA1YzG)
    &#x20;

:::hint{type="info"}
If you are having any questions about which approach to proceed with integration, please feel free to submit a support [ticket](https://help.klevu.com/support/tickets/new) and one of our solution engineers will set up a call to go through your requirements and suggest the recommended approach.&#x20;
:::




[title] Personalisation
[path] Guide/Smart Search/

:::hint{type="warning"}
The personalisation is an add-on feature. To enable the option, please submit a support [ticket](https://help.klevu.com/support/tickets/new)
:::

When a customer enters a physical shop, they may express their preferences to an in-store assistant by highlighting the colours they like, the brands they prefer and what they have purchased before.

The in-store assistant would then use this information to show the customer products they are most likely interested in first, before showing them any others that still may be suitable.

Klevu A.I. is your online assistant.

This personalisation can be provided in two ways:

1. including some information about the customer's browsing history with each request
2. defining your own boosting rules based on the information you already know about the customer

You can read more about how this works in our [Personalisation Guide](https://help.klevu.com/support/solutions/articles/5000871361-do-you-offer-apis-for-personalisation-).

## Browsing History

If you provide the IDs of products which the customer has recently interacted with, the Klevu A.I. will figure out the common aspects of those products and influence the search results.

The easiest way to highlight this is with an example:

- In the JSON below, the four record IDs provided within context represent the products that a customer has clicked on before making a search. They all have the brand 'MNH'.
- There may be other attributes those products have in common, such as price, color, material, etc., however, we have specified in the query that we are only interested in personalisation based on 'brand'.
- When you execute the query, you will see some brand 'MNH' results are coming first.

Note that the impact of personalisation is not always apparent. **Klevu is clever.** If the customer has recently been looking at 'shoes' but now they are searching for 'washing machines', Klevu will know to disregard any interactions that are not relevant to the current search query.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "History",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "enablePersonalisation",
        "type": "Boolean",
        "description": "This must be set to 'true' for enabling personalisation on a particular request. If set to 'false', the recent objects within the context object will be ignored"
      },
      {
        "kind": "optional",
        "name": "fields",
        "type": "Array",
        "description": "This is an optional field. By default, Klevu will analyse all attributes of the records the customer has interacted with, in order to determine the common patterns. If you prefer to focus on particular aspects, for example brand or price, specify those attributes within this object."
      },
      {
        "kind": "optional",
        "name": "recentObjects",
        "type": "Object",
        "description": "Use this object to specify the records (e.g. products, categories, etc.) that were recently interacted with by a customer.\n\nPlease only specify one recentObject object per record type, one for all KLEVU_PRODUCT entries, another for all KLEVU_CMS pages visited, etc.\n\nEach recentObject object may contain multiple record objects (e.g. 5 recently viewed products). The most recently clicked record should be the first element in the array."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n   meta: {\n      qTime: 22,\n      responseCode: 200\n   },\n   queryResults: [\n      {\n         id: \"productSearch\",\n         meta: {\n            qTime: 7,\n            noOfResults: 5,\n            totalResultsFound: 104,\n            typeOfSearch: \"WILDCARD_AND\",\n            offset: 0,\n            debuggingInformation: {},\n            notificationCode: 1,\n            searchedTerm: \"short\",\n            apiKey: \"klevu-156925593843210765\",\n            isPersonalised: false\n         },\n         records: [\n            {\n               name: \"Erika Running Short\",\n               id: \"31366431014974\",\n               brand: \"KSD\"\n            },\n            {\n               name: \"Erika Running Short\",\n               id: \"31366431080510\",\n               brand: \"KSD\"\n            },\n            {\n               name: \"Erika Running Short\",\n               id: \"31366431146046\",\n               brand: \"KSD\"\n            },\n            {\n               name: \"Meteor Workout Short\",\n               id: \"31366465781822\",\n               brand: \"KKE\"\n            },\n            {\n               name: \"Hawkeye Yoga Short\",\n               id: \"31366465126462\",\n               brand: \"MNH\"\n            }\n         ],\n         filters: []\n      }\n   ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"productSearch\",\n      \"settings\": {\n        \"personalisation\": {\n          \"enablePersonalisation\": true,\n          \"fields\": [\n            \"brand\"\n          ]\n        },\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": \"31366487507006\"\n                },\n                {\n                  \"id\": \"31366466633790\"\n                },\n                {\n                  \"id\": \"31366456311870\"\n                },\n                {\n                  \"id\": \"31366467944510\"\n                }\n              ]\n            }\n          ]\n        },\n        \"id\": \"productSearch\",\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"limit\": 5,\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"brand\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}\n",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"settings\": {\n        \"personalisation\": {\n          \"enablePersonalisation\": true,\n          \"fields\": [\n            \"brand\"\n          ]\n        },\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": \"31366487507006\"\n                },\n                {\n                  \"id\": \"31366466633790\"\n                },\n                {\n                  \"id\": \"31366456311870\"\n                },\n                {\n                  \"id\": \"31366467944510\"\n                }\n              ]\n            }\n          ]\n        },\n        \"id\": \"productSearch\",\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"limit\": 5,\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"brand\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}\n',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"settings\":{\"personalisation\":{\"enablePersonalisation\":true,\"fields\":[\"brand\"]},\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":\"31366487507006\"},{\"id\":\"31366466633790\"},{\"id\":\"31366456311870\"},{\"id\":\"31366467944510\"}]}]},\"id\":\"productSearch\",\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"limit\":5,\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"brand\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"settings\\\": {\\n        \\\"personalisation\\\": {\\n          \\\"enablePersonalisation\\\": true,\\n          \\\"fields\\\": [\\n            \\\"brand\\\"\\n          ]\\n        },\\n        \\\"context\\\": {\\n          \\\"recentObjects\\\": [\\n            {\\n              \\\"typeOfRecord\\\": \\\"KLEVU_PRODUCT\\\",\\n              \\\"records\\\": [\\n                {\\n                  \\\"id\\\": \\\"31366487507006\\\"\\n                },\\n                {\\n                  \\\"id\\\": \\\"31366466633790\\\"\\n                },\\n                {\\n                  \\\"id\\\": \\\"31366456311870\\\"\\n                },\\n                {\\n                  \\\"id\\\": \\\"31366467944510\\\"\\n                }\\n              ]\\n            }\\n          ]\\n        },\\n        \\\"id\\\": \\\"productSearch\\\",\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"limit\\\": 5,\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"brand\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\\n\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"settings\":{\"personalisation\":{\"enablePersonalisation\":true,\"fields\":[\"brand\"]},\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":\"31366487507006\"},{\"id\":\"31366466633790\"},{\"id\":\"31366456311870\"},{\"id\":\"31366467944510\"}]}]},\"id\":\"productSearch\",\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"limit\":5,\"query\":{\"term\":\"short\"},\"fields\":[\"id\",\"name\",\"brand\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to utilize the recently visited products to personlised the search results. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "history",
  "legacyHash": "cVtHNg4I1vpGHYXdkQ-0n"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=browsingHistory&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::

## Known Preferences

If you have already built up a profile of your customer and would like to use what you know about them to promote certain results, you can use the boost object within each record query.

There are three ways the records can be boosted:

- filter conditions
- keywords or phrases
- IDs of specific records

For example, let's say you have an online store with an area where customers can log in.

- From your store's purchase history, you know that one customer is particularly interested in the brand 'KKE'.
- From your analytics data, you also know the same customer also looked at the product detail page of the product with ID: '31366487375934' many times.
- Finally, you have an area where customers can specify keywords of their interests, and this customer wrote 'comfortable'.

As a merchant with all of this information available, you can build up a profile about this customer. The sample to the right shows how you would convey this information to Klevu during a search.

To find out more about how boosting works with your existing merchandising rules, please read this article on [How Personalisation Works](https://help.klevu.com/support/solutions/articles/5000871357-how-does-it-work-).

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Known preferences",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "filters",
        "type": "Array",
        "description": "Specify filter values to apply a boosting score to. They key is the unique identifier of the attribute, eg. Color. Each of the values represents the value of that filter to boost, eg. red or blue."
      },
      {
        "kind": "optional",
        "name": "keywords",
        "type": "Array",
        "description": "Specify keywords or phrases to apply a boosting score to, for example \"comfortable\"."
      },
      {
        "kind": "optional",
        "name": "records",
        "type": "Array",
        "description": "Specify the Klevu ID of any records to apply a boosting score to."
      },
      {
        "kind": "optional",
        "name": "weight",
        "type": "Number",
        "description": "The boosting value to be applied, a decimal between 0 - 999. Please specify values above 1 for boosting the records up the rankings, and a value of 0 to 1 to de-boost records down the rankings."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 16,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 13,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 104,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431146046\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431014974\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"name\": \"Erika Running Short\",\n                    \"id\": \"31366431080510\",\n                    \"brand\": \"KSD\"\n                },\n                {\n                    \"name\": \"Meteor Workout Short\",\n                    \"id\": \"31366465781822\",\n                    \"brand\": \"KKE\"\n                },\n                {\n                    \"name\": \"Hawkeye Yoga Short\",\n                    \"id\": \"31366465191998\",\n                    \"brand\": \"KKE\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"boost\": {\n        \"filters\": [\n          {\n            \"key\": \"brand\",\n            \"values\": [\"KKE\"],\n            \"weight\": 200\n          },\n          {\n            \"key\": \"brand\",\n            \"values\": [\"MNH\", \"KSD\"],\n            \"weight\": 150\n          }\n        ],\n        \"keywords\": [\n          {\n            \"phrase\": \"comfortable\",\n            \"weight\": 100\n          }\n        ],\n        \"records\": [\n          {\n            \"id\": \"31366487375934\",\n            \"weight\": 300\n          }\n        ]\n      },\n      \"id\": \"productSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"brand\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}\n",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"boost\": {\n        \"filters\": [\n          {\n            \"key\": \"brand\",\n            \"values\": [\"KKE\"],\n            \"weight\": 200\n          },\n          {\n            \"key\": \"brand\",\n            \"values\": [\"MNH\", \"KSD\"],\n            \"weight\": 150\n          }\n        ],\n        \"keywords\": [\n          {\n            \"phrase\": \"comfortable\",\n            \"weight\": 100\n          }\n        ],\n        \"records\": [\n          {\n            \"id\": \"31366487375934\",\n            \"weight\": 300\n          }\n        ]\n      },\n      \"id\": \"productSearch\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"brand\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}\n',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"boost\":{\"filters\":[{\"key\":\"brand\",\"values\":[\"KKE\"],\"weight\":200},{\"key\":\"brand\",\"values\":[\"MNH\",\"KSD\"],\"weight\":150}],\"keywords\":[{\"phrase\":\"comfortable\",\"weight\":100}],\"records\":[{\"id\":\"31366487375934\",\"weight\":300}]},\"id\":\"productSearch\",\"settings\":{\"query\":{\"term\":\"short\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\",\"brand\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"boost\\\": {\\n        \\\"filters\\\": [\\n          {\\n            \\\"key\\\": \\\"brand\\\",\\n            \\\"values\\\": [\\\"KKE\\\"],\\n            \\\"weight\\\": 200\\n          },\\n          {\\n            \\\"key\\\": \\\"brand\\\",\\n            \\\"values\\\": [\\\"MNH\\\", \\\"KSD\\\"],\\n            \\\"weight\\\": 150\\n          }\\n        ],\\n        \\\"keywords\\\": [\\n          {\\n            \\\"phrase\\\": \\\"comfortable\\\",\\n            \\\"weight\\\": 100\\n          }\\n        ],\\n        \\\"records\\\": [\\n          {\\n            \\\"id\\\": \\\"31366487375934\\\",\\n            \\\"weight\\\": 300\\n          }\\n        ]\\n      },\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"brand\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\\n\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"boost\":{\"filters\":[{\"key\":\"brand\",\"values\":[\"KKE\"],\"weight\":200},{\"key\":\"brand\",\"values\":[\"MNH\",\"KSD\"],\"weight\":150}],\"keywords\":[{\"phrase\":\"comfortable\",\"weight\":100}],\"records\":[{\"id\":\"31366487375934\",\"weight\":300}]},\"id\":\"productSearch\",\"settings\":{\"query\":{\"term\":\"short\"},\"limit\":5,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\",\"brand\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example how to boost products based on users preference. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "known-preferences-1",
  "legacyHash": "5y9Gfsj5gfl97UEl65YtQ"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=knownPreferences&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Untitled
[path] /


[title] Dashboard/KMC Settings
[path] Guide/

Klevu's [dashboard settings](https://help.klevu.com/support/solutions/articles/5000871314-how-can-i-access-klevu-merchant-center-) are currently accessible via a JSON file exposed over a publicly accessible url.&#x20;




[title] Visually Similar
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any other products from the catalog which are visually similar to the product currently being viewed. This type of recommendation can be used on:

:::hint{type="info"}
Visually Similar recommendation is currently only available for Furniture domain.
:::

**Product Page: Visually Similar Products** Show a recommendation banner with products that are visually similar to the primary image of the product currently being viewed.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Visually Similar Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify RECS_SIMILAR_IMAGES."
      },
      {
        "kind": "required",
        "name": "sourceObjects",
        "type": "Object",
        "description": "The Klevu ID of the product you will use for context. Klevu will find other visually similar products to the primary image of the product specified in this field."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 529,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"klevuRECSItemList\",\n            \"meta\": {\n                \"qTime\": 125,\n                \"noOfResults\": 10,\n                \"totalResultsFound\": 16,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-164270249063714699\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6920770322477\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"2099.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/226507-001_FRT_1_medium.jpg?v=1642666285\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40225085521965\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/226507-001_PRM_1_medium.jpg?v=1642666285\",\n                    \"sku\": \"L0461529\",\n                    \"brand\": \"Lulu and Georgia\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/226507-001_FRT_1_medium.jpg?v=1642666285\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"2099.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - Dressers;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/maeve-dresser\",\n                    \"name\": \"Maeve Dresser\",\n                    \"shortDesc\": \"Simply inspired, this solid dry-washed poplar dresser combines clean lines with dovetail joints in a Shaker-inspired design. This wood dresser is finished in a light neutral tone and fitted with iron and leather hardware and six spacious drawers i\",\n                    \"category\": \"Furniture - Dressers;;Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967619584045\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"9140.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/McQueen-8-drawer-chest-by-Matthew-Hilton_medium.jpg?v=1646906983\",\n                    \"model\": \"12 Drawers\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40412686188589\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/368McQueenLargeChestbyMatthewHiltoninDanishoiledwalnut-whitebkgrnd_medium.png?v=1646906983\",\n                    \"sku\": \"HA159951-1\",\n                    \"brand\": \"De La Espada\",\n                    \"startPrice\": \"6020.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/McQueen-8-drawer-chest-by-Matthew-Hilton_medium.jpg?v=1646906983\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"9140.0\",\n                    \"wood_finish\": \"Walnut/White Oiled\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 19,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/mcqueen-chests-by-matthew-hilton\",\n                    \"tags\": \"designed-by-Matthew Hilton, made-to-order-12\",\n                    \"name\": \"McQueen Chest by Matthew Hilton\",\n                    \"shortDesc\": \"McQueen Chests are strong, elegant and down-to-earth and their wide body and numerous drawers provide maximum storage space. The drawers are detailed with dovetail joinery, cast iron handles, and soft-closing piston action. Details\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967621287981\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"2745.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/McQueen-Bedside-chest-by-Matthew-Hilton_medium.jpg?v=1646907007\",\n                    \"finish\": \"Walnut/Oiled\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40412689137709\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/McQueen-Bedside_Hepburn-Bed.hs_medium.jpg?v=1646907007\",\n                    \"sku\": \"HA102487\",\n                    \"brand\": \"De La Espada\",\n                    \"startPrice\": \"2285.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/McQueen-Bedside-chest-by-Matthew-Hilton_medium.jpg?v=1646907007\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"2745.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - Beds;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 6,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/mcqueen-bedside-chest-by-matthew-hilton\",\n                    \"tags\": \"designed-by-Matthew Hilton, made-to-order-12\",\n                    \"name\": \"McQueen Bedside Chest by Matthew Hilton\",\n                    \"shortDesc\": \"McQueen Bedside Chest is strong, elegant and down-to-earth, its two drawers provide the ideal space for objects needed close to the bed. Drawers are detailed with dovetail joinery, cast iron handles, and soft-closing piston action. Manufact\",\n                    \"category\": \"Furniture - Beds;;Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6968498618413\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"1486.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Carry3_medium.jpg?v=1646947879\",\n                    \"finish\": \"New White\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40415995920429\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Carry4_medium.jpg?v=1646947879\",\n                    \"sku\": \"\",\n                    \"brand\": \"Montana Furniture\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Carry3_medium.jpg?v=1646947879\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"1486.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 4,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/carry-chest-of-drawers-by-montana-furniture\",\n                    \"tags\": \"designed-by-Peter J. Lassen, lead-time-5, new-arrivals\",\n                    \"mounting_type\": \"Free Standing - Legs\",\n                    \"name\": \"Carry Chest of Drawers by Montana Furniture\",\n                    \"shortDesc\": \"Carry is a modern and timeless chest of three drawers providing the ideal storage solution for the living room, the home office or the bedroom. Carry is a chest that consists of three drawers in one row. We have listed the free-standing uni\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967750656045\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"5280.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Mc_Queen_low_chest.hs_medium.jpg?v=1646909088\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40412936536109\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Mc_Queen_low_chest2.hs_medium.jpg?v=1646909088\",\n                    \"sku\": \"HA112590\",\n                    \"brand\": \"De La Espada\",\n                    \"startPrice\": \"5280.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Mc_Queen_low_chest.hs_medium.jpg?v=1646909088\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"5280.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 2,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/mcqueen-low-chest-by-matthew-hilton\",\n                    \"tags\": \"designed-by-Matthew Hilton, made-to-order-12\",\n                    \"name\": \"McQueen Low Chest by Matthew Hilton\",\n                    \"shortDesc\": \"McQueen Chests provide ample storage in classic forms with a beautiful contrast of materials. The solid wood body is punctuated with cast iron drawer pulls and feet. Each drawer front is made from a single plank of timber, carefully chosen for its\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967620894765\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"5020.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/369McQueenTallChestbyMatthewHiltoninDanishoiledwalnut-front-whitebkgrnd_medium.png?v=1646907003\",\n                    \"wood\": \"Ash/Oiled\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40412687990829\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/369McQueenTallChestbyMatthewHiltoninDanishoiledwalnut-whitebkgrnd_medium.png?v=1646907003\",\n                    \"sku\": \"HA112591\",\n                    \"brand\": \"De La Espada\",\n                    \"startPrice\": \"5020.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/369McQueenTallChestbyMatthewHiltoninDanishoiledwalnut-front-whitebkgrnd_medium.png?v=1646907003\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"5020.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/mcqueen-tall-chest-by-matthew-hilton\",\n                    \"tags\": \"designed-by-Matthew Hilton, made-to-order-12\",\n                    \"name\": \"McQueen Tall Chest by Matthew Hilton\",\n                    \"shortDesc\": \"McQueen Chests are strong, elegant and down-to-earth and their wide body and numerous drawers provide maximum storage space. The drawers are detailed with dovetail joinery, cast iron handles, and soft-closing piston action. Details\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6968496259117\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"2237.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Keep5_medium.jpg?v=1646947657\",\n                    \"finish\": \"Nordic\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40415972720685\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Keep4_medium.jpg?v=1646947657\",\n                    \"sku\": \"\",\n                    \"brand\": \"Montana Furniture\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Square-Website-Haus-London-Montana-Keep5_medium.jpg?v=1646947657\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"2237.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 5,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/keep-chest-of-drawers-by-montana-furniture\",\n                    \"tags\": \"designed-by-Peter J. Lassen, lead-time-5, new-arrivals\",\n                    \"mounting_type\": \"Free Standing - Legs\",\n                    \"name\": \"Keep Chest of Drawers by Montana Furniture\",\n                    \"shortDesc\": \"This chest of drawers is ideal to keep everything in order in the bedroom, living room or in the hall.  It is comprised of one large module with four drawers and a\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6968494555181\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"1399.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Haus-London-String-Workspace-Bundle-E2_medium.jpg?v=1646947513&vid=40415958007853\",\n                    \"finish\": \"Black / Black\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40415958007853\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Haus-London-String-Workspace-Bundle-E2_medium.jpg?v=1646947513&vid=40415958007853\",\n                    \"sku\": \"\",\n                    \"brand\": \"String Furniture\",\n                    \"startPrice\": \"1277.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/Haus-London-String-Workspace-Bundle-E2_medium.jpg?v=1646947513&vid=40415958007853\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"1399.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/string-office-bundle-we\",\n                    \"tags\": \"designed-by-Nils Strinning, lead-time-4-6, new-arrivals, r-STRING, string-bundle\",\n                    \"product_type\": \"Furniture\",\n                    \"name\": \"String - Workspace Bundle E\",\n                    \"shortDesc\": \"String Bundles are ready-made combinations using components from the String Storage System.  Whether your works\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967875895341\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"3195.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/matthew_hilton_mcqueen_bedside_medium.jpg?v=1646915437\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40413446602797\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/matthew_hilton_mcqueen_bedside_angle_medium.jpg?v=1646915437\",\n                    \"sku\": \"HA112511\",\n                    \"brand\": \"De La Espada\",\n                    \"startPrice\": \"2660.0\",\n                    \"drawer_unit\": \"Left Hand Side\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/matthew_hilton_mcqueen_bedside_medium.jpg?v=1646915437\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"3195.0\",\n                    \"wood_finish\": \"Walnut/Oiled\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - Beds;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 1,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/mcqueen-bedside-by-matthew-hilton\",\n                    \"tags\": \"designed-by-Matthew Hilton, made-to-order-12\",\n                    \"name\": \"McQueen Bedside Unit by Matthew Hilton\",\n                    \"shortDesc\": \"McQueen bedside unit has a generous storage capacity including shelving and two drawers. It is available as a left or right hand unit, to allow the drawers to be nearest to each side of the bed. McQueen bedside's drawers are detailed with dovetail jo\",\n                    \"category\": \"Furniture - Beds;;Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Furniture\",\n                    \"itemGroupId\": \"6967988191277\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"USD\",\n                    \"price\": \"414.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/string_chest_drawers_oak.hs_medium.jpg?v=1646921585&vid=40413964927021\",\n                    \"finish\": \"Oak\",\n                    \"currency\": \"USD\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"40413964927021\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/string_chest_drawers_white.hs_medium.jpg?v=1646921585&vid=40413964763181\",\n                    \"sku\": \"LH7830-05-1\",\n                    \"brand\": \"String Furniture\",\n                    \"startPrice\": \"356.0\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0564/3730/9485/products/string_chest_drawers_oak.hs_medium.jpg?v=1646921585&vid=40413964927021\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"414.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Furniture - All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://danish-store-livetest3.myshopify.com/products/string-shelving-system-chest-with-drawers\",\n                    \"tags\": \"designed-by-Nils Strinning, lead-time-4-6, r-STRING, string-component\",\n                    \"product_type\": \"Furniture\",\n                    \"size\": \"78cm Wide Chest\",\n                    \"name\": \"String - Chest with Drawers\",\n                    \"shortDesc\": \"String is the original component shelving system. The structure is light weight, yet stable.\",\n                    \"category\": \"Furniture - All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n   \"context\":{\n      \"apiKeys\":[\n         \"klevu-164270249063714699\"\n      ]\n   },\n   \"recordQueries\":[\n      {\n         \"id\":\"klevuRECSItemList\",\n         \"typeOfRequest\":\"RECS_SIMILAR_IMAGES\",\n         \"settings\":{\n            \"typeOfRecords\":[\n               \"KLEVU_PRODUCT\"\n            ],\n            \"limit\":10,\n            \"excludeIds\":[\n               {\n                  \"key\":\"itemGroupId\",\n                  \"value\":\"6920771731501\"\n               }\n            ],\n            \"context\":{\n               \"sourceObjects\":[\n                  {\n                     \"typeOfRecord\":\"KLEVU_PRODUCT\",\n                     \"records\":[\n                        {\n                           \"itemGroupId\":\"6920771731501\"\n                        },\n                        {\n                           \"id\":\"40225093124141\"\n                        }\n                     ]\n                  }\n               ]\n            }\n         }\n      }\n   ]\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs28v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n   \"context\":{\n      \"apiKeys\":[\n         \"klevu-164270249063714699\"\n      ]\n   },\n   \"recordQueries\":[\n      {\n         \"id\":\"klevuRECSItemList\",\n         \"typeOfRequest\":\"RECS_SIMILAR_IMAGES\",\n         \"settings\":{\n            \"typeOfRecords\":[\n               \"KLEVU_PRODUCT\"\n            ],\n            \"limit\":10,\n            \"excludeIds\":[\n               {\n                  \"key\":\"itemGroupId\",\n                  \"value\":\"6920771731501\"\n               }\n            ],\n            \"context\":{\n               \"sourceObjects\":[\n                  {\n                     \"typeOfRecord\":\"KLEVU_PRODUCT\",\n                     \"records\":[\n                        {\n                           \"itemGroupId\":\"6920771731501\"\n                        },\n                        {\n                           \"id\":\"40225093124141\"\n                        }\n                     ]\n                  }\n               ]\n            }\n         }\n      }\n   ]\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-164270249063714699\"]},\"recordQueries\":[{\"id\":\"klevuRECSItemList\",\"typeOfRequest\":\"RECS_SIMILAR_IMAGES\",\"settings\":{\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"limit\":10,\"excludeIds\":[{\"key\":\"itemGroupId\",\"value\":\"6920771731501\"}],\"context\":{\"sourceObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"itemGroupId\":\"6920771731501\"},{\"id\":\"40225093124141\"}]}]}}}]});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs28v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n   \\\"context\\\":{\\n      \\\"apiKeys\\\":[\\n         \\\"klevu-164270249063714699\\\"\\n      ]\\n   },\\n   \\\"recordQueries\\\":[\\n      {\\n         \\\"id\\\":\\\"klevuRECSItemList\\\",\\n         \\\"typeOfRequest\\\":\\\"RECS_SIMILAR_IMAGES\\\",\\n         \\\"settings\\\":{\\n            \\\"typeOfRecords\\\":[\\n               \\\"KLEVU_PRODUCT\\\"\\n            ],\\n            \\\"limit\\\":10,\\n            \\\"excludeIds\\\":[\\n               {\\n                  \\\"key\\\":\\\"itemGroupId\\\",\\n                  \\\"value\\\":\\\"6920771731501\\\"\\n               }\\n            ],\\n            \\\"context\\\":{\\n               \\\"sourceObjects\\\":[\\n                  {\\n                     \\\"typeOfRecord\\\":\\\"KLEVU_PRODUCT\\\",\\n                     \\\"records\\\":[\\n                        {\\n                           \\\"itemGroupId\\\":\\\"6920771731501\\\"\\n                        },\\n                        {\\n                           \\\"id\\\":\\\"40225093124141\\\"\\n                        }\\n                     ]\\n                  }\\n               ]\\n            }\\n         }\\n      }\\n   ]\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs28v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs28v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-164270249063714699\"]},\"recordQueries\":[{\"id\":\"klevuRECSItemList\",\"typeOfRequest\":\"RECS_SIMILAR_IMAGES\",\"settings\":{\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"limit\":10,\"excludeIds\":[{\"key\":\"itemGroupId\",\"value\":\"6920771731501\"}],\"context\":{\"sourceObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"itemGroupId\":\"6920771731501\"},{\"id\":\"40225093124141\"}]}]}}}]})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "The end-point is used for retrieving visually similar product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "visually-similar-product-recommendations",
  "legacyHash": "fLaTTKGPnHR_03nxKRhN1"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=visuallySimilar&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Faceting
[path] Guide/Smart Search/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

:::hint{type="warning"}
It is important to note that retrieving filters is an expensive operation that can slow down your search experience. For this reason, you may want to fetch filters once per unique query and cache them locally.



For example, when using pagination to retrieve records from subsequent pages, there is actually no need to fetch the filters again since these will not change from page to page. The filters from Klevu are always for the entire set of records for that query.
:::

While searching for records, you can also request aggregations of the attribute values within the search results, so you can allow your customers to filter the results further.

For example, if the search query was "tops", you may also be interested to know all of the colors, sizes, and materials that these tops are available in to display them as selectable facets or filters.

There are two separate methods of working with filters with the Klevu search API:

- Retrieving filters applicable to a search result
- Applying one or more of those filters to a search query

To apply a filter, you need to know the key of the relevant filter and the value of the relevant option, which should be submitted using the same format and case sensitivity as is returned by Klevu.

## Retrieving Facets

The filtersToReturn object can be used for obtaining filters from the Klevu Search engine. You can request all possible filters or only those matching certain criteria.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Retrieving facets",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "optional",
        "name": "enabled",
        "type": "Boolean",
        "description": "Whether or not to return any filters with this query. This defaults to false so no filters are returned unless requested."
      },
      {
        "kind": "optional",
        "name": "include",
        "type": "Array",
        "description": "This is the list of filter keys that you would like to retrieve as filters. A filter may also not be returned if there aren't enough applicable records in the result set."
      },
      {
        "kind": "optional",
        "name": "exclude",
        "type": "Array",
        "description": "This is the list of filter keys that you do not want Klevu Search to include in the response. If a filter is specified in both include and exclude lists, include will take precedence."
      },
      {
        "kind": "optional",
        "name": "options",
        "type": "Object",
        "description": "Specify how the filters' options are included in the response.\n\norder: A value of 'FREQ' will sort options based on the number of records each option has in the result set. 'INDEX' will sort the options alphabetically.\n\nlimit: Specify the maximum number of options to be included per filter.\n\nminCount: If the parameter minCount is present with a positive number, only the options with an option count equal to or higher than the minCount are included."
      },
      {
        "kind": "optional",
        "name": "rangeFilterSettings",
        "type": "Object",
        "description": "When minMax is false, this setting allows you to retrieve range filters for use with numeric values such as price, so you can display bands of 0-99, 100-199, etc. or a price slider.\n\nkey: This is the identifier of your numerical attribute, eg. 'klevu_price'.\n\nminMax: If set to true, the Klevu Search engine calculates the minimum and maximum values for this filter for use with a slider.\n\nrangeInterval: If a positive value is provided, the Klevu Search engine will calculate ranges for this value. For example a value of 100 would give ranges from 0 to 99, 100 to 299, etc.\n\nBy default all attributes submitted to Klevu are indexed as STRING attributes, which means they cannot be used as range filters. The product sale price field is the only exception to this rule, which is filtered using the key klevu_price. If you have explicitly requested and Klevu has approved that certain attributes be indexed as numerical attributes, you can also retrieve those as range filters."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 19,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 17,\n                \"noOfResults\": 0,\n                \"totalResultsFound\": 104,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [],\n            \"filters\": [\n                {\n                    \"key\": \"category\",\n                    \"label\": \"category\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 3,\n                            \"name\": \"Capri\",\n                            \"value\": \"Capri\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 3,\n                            \"name\": \"Hoodies\",\n                            \"value\": \"Hoodies\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 3,\n                            \"name\": \"Hoodies & Sweatshirts\",\n                            \"value\": \"Hoodies & Sweatshirts\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 3,\n                            \"name\": \"Pants\",\n                            \"value\": \"Pants\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 68,\n                            \"name\": \"Shorts\",\n                            \"value\": \"Shorts\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"size\",\n                    \"label\": \"Size\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 35,\n                            \"name\": \"Large\",\n                            \"value\": \"Large\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 35,\n                            \"name\": \"Medium\",\n                            \"value\": \"Medium\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 34,\n                            \"name\": \"Small\",\n                            \"value\": \"Small\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"brand\",\n                    \"label\": \"brand\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 28,\n                            \"name\": \"KKE\",\n                            \"value\": \"KKE\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 1,\n                            \"name\": \"KKE New\",\n                            \"value\": \"KKE New\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 45,\n                            \"name\": \"KSD\",\n                            \"value\": \"KSD\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 30,\n                            \"name\": \"MNH\",\n                            \"value\": \"MNH\",\n                            \"selected\": false\n                        }\n                    ]\n                },\n                {\n                    \"key\": \"Price Range\",\n                    \"label\": \"Price Range\",\n                    \"type\": \"OPTIONS\",\n                    \"options\": [\n                        {\n                            \"count\": 95,\n                            \"name\": \"0 - 49\",\n                            \"value\": \"0 - 49\",\n                            \"selected\": false\n                        },\n                        {\n                            \"count\": 9,\n                            \"name\": \"50 - 99\",\n                            \"value\": \"50 - 99\",\n                            \"selected\": false\n                        }\n                    ]\n                }\n            ]\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"filters\": {\n        \"filtersToReturn\": {\n          \"enabled\": true,\n          \"include\": [\n            \"category\",\n            \"brand\",\n            \"size\"\n          ],\n          \"options\": {\n            \"order\": \"INDEX\",\n            \"limit\": 5\n          },\n          \"rangeFilterSettings\": [\n            {\n              \"key\": \"klevu_price\",\n              \"minMax\": false,\n              \"rangeInterval\": 50\n            },\n            {\n              \"key\": \"CustomRangeFilter\",\n              \"minMax\": true\n            }\n          ]\n        }\n      },\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"searchPrefs\": [\n          \"showFiltersWithSmallCount\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 0,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"filters\": {\n        \"filtersToReturn\": {\n          \"enabled\": true,\n          \"include\": [\n            \"category\",\n            \"brand\",\n            \"size\"\n          ],\n          \"options\": {\n            \"order\": \"INDEX\",\n            \"limit\": 5\n          },\n          \"rangeFilterSettings\": [\n            {\n              \"key\": \"klevu_price\",\n              \"minMax\": false,\n              \"rangeInterval\": 50\n            },\n            {\n              \"key\": \"CustomRangeFilter\",\n              \"minMax\": true\n            }\n          ]\n        }\n      },\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"searchPrefs\": [\n          \"showFiltersWithSmallCount\"\n        ],\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 0,\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ],\n        \"fields\": [\n          \"id\",\n          \"name\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"filters\":{\"filtersToReturn\":{\"enabled\":true,\"include\":[\"category\",\"brand\",\"size\"],\"options\":{\"order\":\"INDEX\",\"limit\":5},\"rangeFilterSettings\":[{\"key\":\"klevu_price\",\"minMax\":false,\"rangeInterval\":50},{\"key\":\"CustomRangeFilter\",\"minMax\":true}]}},\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"searchPrefs\":[\"showFiltersWithSmallCount\"],\"query\":{\"term\":\"short\"},\"limit\":0,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"filters\\\": {\\n        \\\"filtersToReturn\\\": {\\n          \\\"enabled\\\": true,\\n          \\\"include\\\": [\\n            \\\"category\\\",\\n            \\\"brand\\\",\\n            \\\"size\\\"\\n          ],\\n          \\\"options\\\": {\\n            \\\"order\\\": \\\"INDEX\\\",\\n            \\\"limit\\\": 5\\n          },\\n          \\\"rangeFilterSettings\\\": [\\n            {\\n              \\\"key\\\": \\\"klevu_price\\\",\\n              \\\"minMax\\\": false,\\n              \\\"rangeInterval\\\": 50\\n            },\\n            {\\n              \\\"key\\\": \\\"CustomRangeFilter\\\",\\n              \\\"minMax\\\": true\\n            }\\n          ]\\n        }\\n      },\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\n      \\\"settings\\\": {\\n        \\\"searchPrefs\\\": [\\n          \\\"showFiltersWithSmallCount\\\"\\n        ],\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"limit\\\": 0,\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ],\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"filters\":{\"filtersToReturn\":{\"enabled\":true,\"include\":[\"category\",\"brand\",\"size\"],\"options\":{\"order\":\"INDEX\",\"limit\":5},\"rangeFilterSettings\":[{\"key\":\"klevu_price\",\"minMax\":false,\"rangeInterval\":50},{\"key\":\"CustomRangeFilter\",\"minMax\":true}]}},\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"searchPrefs\":[\"showFiltersWithSmallCount\"],\"query\":{\"term\":\"short\"},\"limit\":0,\"typeOfRecords\":[\"KLEVU_PRODUCT\"],\"fields\":[\"id\",\"name\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "This is an example to fetch facets. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "retrieving-facets-1",
  "legacyHash": "wQg61HLEV_qi7kEjMZKK2"
}
```
:::

**Understanding response format**

| **Params**           | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |   |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - |
| key                  | This is the unique identifier of the attribute for which options are being provided.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |   |
| label                | This is the label or caption which you have associated with the attribute in the Klevu Merchant Centre.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |   |
| type                 | The type of the filter will be either OPTIONS, SLIDER or RATING. For an OPTIONS filter, its different options, eg. red, blue, black, are provided. &#xA;For a SLIDER filter, values such as minimum, maximum, start and end are provided in the response. &#xA;For a RATING filter, its rating ranges from 1 to 5, where Range is defined as below:&#xA;The rating range of 4.51 - 5.5 is considered the 5 rating<br />The rating range of 3.51 - 4.5 is considered the 4 rating<br />The rating range of 2.51 - 3.5 is considered the 3 rating<br />The rating range of 1.51 - 2.5 is considered the 2 rating<br />The rating less than 1.50 is considered 1 Rating |   |
| options              | For type OPTIONS this will contain an array of different options available.&#xA;**name**: The label or caption of the option, eg. Red, Blue, Black, etc.&#xA;**value**: This is the unique identifier which should be used when applying a filter to search results.&#xA;**count**: The number of records found with the current option in the current search results.&#xA;**selected**: Whether ot not the current option is already applied as a filtering condition on the search results.                                                                                                                                                                        |   |
| min, max, start, end | These values are provided only for the SLIDER or range filters.&#xA;min, max: These values are the minimum and maximum values found in the current result set. This can be used to set the upper and lower limits of your slider.&#xA;start, end: The start and end values are the filtering conditions already applied on the result set for this filter, or NULL if no filter has been applied.                                                                                                                                                                                                                                                                    |   |

## Applying Facets

The applyFilters object can be used for applying filter conditions so your customers can fine-tune their results based on relevant attributes.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Applying facets",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "key",
        "type": "String",
        "description": "The ID of the attribute to filter by, eg. color"
      },
      {
        "kind": "required",
        "name": "values",
        "type": "Array",
        "description": "An array of values to filter by, eg. Red, Blue.\n\nWhen using range filters, specify the first value as the minimum value and the second as the max value. For example to retrieve records with prices between 60 to 80, use: \"key\": \"klevu_price\", \"values\": [60, 80].\n\nTo retrieve steps of prices, for example those with values between 0-50 or 150-200, use: \"key\": \"klevu_price\", \"values\": [\"0-50\", \"150-200\"].\n\nTo retrieve exact values, for example records with exact values 100 or 200, use: \"key\": \"klevu_price\", \"values\": [\"100-100\", \"200-200\"].\n\nBy default all attributes submitted to Klevu are indexed as STRING attributes, which means they cannot be used as range filters. The product sale price field is the only exception to this rule, which is filtered using the key klevu_price. If you have explicitly requested and Klevu has approved that certain attributes be indexed as numerical attributes, you can also retrieve those as range filters."
      },
      {
        "kind": "optional",
        "name": "singleSelect",
        "type": "Boolean",
        "description": "The behaviour when specifying multiple filters or values. "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 23,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"productSearch\",\n            \"meta\": {\n                \"qTime\": 20,\n                \"noOfResults\": 5,\n                \"totalResultsFound\": 15,\n                \"typeOfSearch\": \"FUZZY_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"short\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"size\": \"Small\",\n                    \"salePrice\": \"75.0\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"id\": \"31366456541246\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"salePrice\": \"74.0\",\n                    \"name\": \"impulse Duffle\",\n                    \"id\": \"31366490095678\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"salePrice\": \"69.0\",\n                    \"name\": \"Ajax Full-Zip Sweatshirt\",\n                    \"id\": \"31366490554430\"\n                },\n                {\n                    \"size\": \"Small\",\n                    \"salePrice\": \"64.0\",\n                    \"name\": \"Grayson Crewneck Sweatshirt\",\n                    \"id\": \"31366490914878\"\n                },\n                {\n                    \"size\": \"Large\",\n                    \"salePrice\": \"64.0\",\n                    \"name\": \"Grayson Crewneck Sweatshirt\",\n                    \"id\": \"31366490816574\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"filters\": {\n        \"applyFilters\": {\n          \"filters\": [\n            {\n              \"key\": \"size\",\n              \"values\": [\n                \"Small\",\n                \"Large\"\n              ],\n              \"settings\": {\n                \"singleSelect\": false\n              }\n            },\n            {\n              \"key\": \"klevu_price\",\n              \"values\": [\n                  \"60\",\n                  \"80\"\n              ],\n              \"settings\": {\n                  \"singleSelect\": false\n              }\n            }\n          ]\n        }\n      },\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"size\",\n          \"klevu_price\"\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"filters\": {\n        \"applyFilters\": {\n          \"filters\": [\n            {\n              \"key\": \"size\",\n              \"values\": [\n                \"Small\",\n                \"Large\"\n              ],\n              \"settings\": {\n                \"singleSelect\": false\n              }\n            },\n            {\n              \"key\": \"klevu_price\",\n              \"values\": [\n                  \"60\",\n                  \"80\"\n              ],\n              \"settings\": {\n                  \"singleSelect\": \"false\"\n              }\n            }\n          ]\n        }\n      },\n      \"id\": \"productSearch\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"query\": {\n          \"term\": \"short\"\n        },\n        \"limit\": 5,\n        \"fields\": [\n          \"id\",\n          \"name\",\n          \"size\",\n          \"klevu_price\"\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"filters\":{\"applyFilters\":{\"filters\":[{\"key\":\"size\",\"values\":[\"Small\",\"Large\"],\"settings\":{\"singleSelect\":false}},{\"key\":\"klevu_price\",\"values\":[\"60\",\"80\"],\"settings\":{\"singleSelect\":\"false\"}}]}},\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"query\":{\"term\":\"short\"},\"limit\":5,\"fields\":[\"id\",\"name\",\"size\",\"klevu_price\"],\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"filters\\\": {\\n        \\\"applyFilters\\\": {\\n          \\\"filters\\\": [\\n            {\\n              \\\"key\\\": \\\"size\\\",\\n              \\\"values\\\": [\\n                \\\"Small\\\",\\n                \\\"Large\\\"\\n              ],\\n              \\\"settings\\\": {\\n                \\\"singleSelect\\\": false\\n              }\\n            },\\n            {\\n              \\\"key\\\": \\\"klevu_price\\\",\\n              \\\"values\\\": [\\n                  \\\"60\\\",\\n                  \\\"80\\\"\\n              ],\\n              \\\"settings\\\": {\\n                  \\\"singleSelect\\\": \\\"false\\\"\\n              }\\n            }\\n          ]\\n        }\\n      },\\n      \\\"id\\\": \\\"productSearch\\\",\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"term\\\": \\\"short\\\"\\n        },\\n        \\\"limit\\\": 5,\\n        \\\"fields\\\": [\\n          \\\"id\\\",\\n          \\\"name\\\",\\n          \\\"size\\\",\\n          \\\"klevu_price\\\"\\n        ],\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"filters\":{\"applyFilters\":{\"filters\":[{\"key\":\"size\",\"values\":[\"Small\",\"Large\"],\"settings\":{\"singleSelect\":false}},{\"key\":\"klevu_price\",\"values\":[\"60\",\"80\"],\"settings\":{\"singleSelect\":\"false\"}}]}},\"id\":\"productSearch\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"query\":{\"term\":\"short\"},\"limit\":5,\"fields\":[\"id\",\"name\",\"size\",\"klevu_price\"],\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "jSU7DlYyJ_eUh63YSP682"
  },
  "description": "This is an example to apply facets. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "applying-facets-1",
  "legacyHash": "-cuXkCfq7dDkIJE4eLqAv"
}
```
:::

**Understanding response format**

If only one filter is applied with only value, Klevu search ensures that all the records returned contain the relevant attribute with the specified value.

In the case where two or more values for the same filter are provided, the execution is dependent on the value of the singleSelect parameter.

- If it is set to true, the products returned must have both the values.
- If it is set to false, the products returned must have at least one of the values.

If constraints are added for multiple filters and the value of the singleSelect filter is false, the products returned must have at least one value from each of the filter conditions provided.

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=faceting&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Customers Also Viewed
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any products which other customers also viewed, in addition to viewing the current product. The most common placements for this banner type are:

**Product Page: Others Also Viewed**
Show a recommendation banner with products other customers viewed from the store.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Customers Also Viewed Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify RECS_ALSO_VIEWED."
      },
      {
        "kind": "required",
        "name": "recentObjects",
        "type": "String",
        "description": "The Klevu ID of the product or products you will use for context. Klevu will find other products which were viewed in addition to the ones specified in this field."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 12,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsAlsoViewed\",\n            \"meta\": {\n                \"qTime\": 8,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 7,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192749842563\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322423840899\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882422-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-printed-hooded-oversize-knitted-sweatshirt\",\n                    \"name\": \"WoMen's Printed Hooded Oversize Knitted Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"White Hoodie thin\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753152131\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"51.42\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=34322460016771,34322460573827,34322461032579,34322461491331,34322461982851,34322462474371,34322463031427\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322461032579\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797422_medium.jpg?v=1611184206&vid=34322466177155,34322466603139,34322466930819,34322467192963,34322467586179,34322467946627,34322468339843\",\n                    \"sku\": \"30504298-white-hoodie-thin-asian-xxxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"48.48\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=34322460016771,34322460573827,34322461032579,34322461491331,34322461982851,34322462474371,34322463031427\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"51.42\",\n                    \"swatchesInfo\": \"variantColor1:Black Hoodie thin ;;;; variantColor3:Blue Hoodie thick ;;;; variantColor2:White Hoodie thick ;;;; variantColor5:White Hoodie thin ;;;; variantColor4:Black Hoodie thick ;;;; variantColor6:Yellow Hoodie thin ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=16847225487491 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797419_medium.jpg?v=1611184206&vid=16847185313923 ;;;; variantId6:34322463555715 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=16847185510531 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=16847190851715 ;;;; variantId4:34322456838275 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797418_medium.jpg?v=1611184250&vid=16847223521411 ;;;; variantId5:34322460016771 ;;;; variantId2:34322452512899 ;;;; variantId3:34322453889155 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797425_medium.jpg?v=1611184240&vid=16847221883011 ;;;; variantId1:34322448646275 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 2,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-hoodies-men-women-2021-spring-sweatshirt-male-japanese-streetwear-oversized-yellow-anime-hoodie-men-sweatshirts\",\n                    \"size\": \"Asian-XXXL\",\n                    \"name\": \"Singleroad Men's Hoodies Men Women 2021 Sweatshirt Male Japanese Streetwear Oversized Anime Hoodie Men Sweatshirts\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753021059\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904686096515\",\n                    \"price\": \"31.98\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920649_medium.jpg?v=1611183859&vid=34322452840579,34322453397635,34322454085763,34322454642819,34322455134339,34322455691395,34322456248451,34322456739971\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322456739971\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920649_medium.jpg?v=1611183859&vid=34322452840579,34322453397635,34322454085763,34322454642819,34322455134339,34322455691395,34322456248451,34322456739971\",\n                    \"sku\": \"39748242-black-xxxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920649_medium.jpg?v=1611183859&vid=34322452840579,34322453397635,34322454085763,34322454642819,34322455134339,34322455691395,34322456248451,34322456739971\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"31.98\",\n                    \"swatchesInfo\": \"variantColor1:Gray ;;;; variantColor3:Yellow ;;;; variantColor2:Black ;;;; variantColor5:Red ;;;; variantColor4:White ;;;; variantColor6:Pink ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantSwatchImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920651_medium.jpg?v=1611183859&vid=16847175090307 ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/pink.png?v=1587554099 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920654_medium.jpg?v=1611184242&vid=16847222177923 ;;;; variantId6:34322469781635 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920649_medium.jpg?v=1611183859&vid=16847172206723 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920652_medium.jpg?v=1611183953&vid=16847193014403 ;;;; variantId4:34322461720707 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920653_medium.jpg?v=1611183915&vid=16847184756867 ;;;; variantId5:34322466046083 ;;;; variantId2:34322452840579 ;;;; variantId3:34322457329795 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1512920650_medium.jpg?v=1611184215&vid=16847218770051 ;;;; variantId1:34322447663235 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/anime-hunter-x-hunter-hoodies-yellow-black-hoodies-killua-long-sleeves-hoodies-sweatshirts-women-streetwear-hooded-for-men-cs370\",\n                    \"size\": \"XXXL\",\n                    \"name\": \"Anime Hunter X Hunter Hoodies Hoodies Killua Long Sleeves Hoodies Sweatshirts Women Streetwear Hooded For Men Cs370\",\n                    \"shortDesc\": \"closure:closure:none; ;;;; Brand Name: KOSMO MASA Sleeve Length(cm): Full Style: Casual Pattern Type: Print\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Dark Grey\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754593923\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"32.08\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340732_medium.jpg?v=1611183864&vid=34322540724355,34322541707395,34322542559363,34322543313027,34322545606787,34322546688131\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322546688131\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340730_medium.jpg?v=1611183859&vid=34322527256707,34322528370819,34322529583235,34322530795651,34322534236291,34322535317635\",\n                    \"sku\": \"37965190-dark-grey-xxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"16.88\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340732_medium.jpg?v=1611183864&vid=34322540724355,34322541707395,34322542559363,34322543313027,34322545606787,34322546688131\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.08\",\n                    \"swatchesInfo\": \"variantColor1:Purple ;;;; variantColor3:Yellow ;;;; variantColor2:Red ;;;; variantColor5:Yellow ;;;; variantColor4:Red ;;;; variantColor6:Navy Blue ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340739_medium.jpg?v=1611183981&vid=16847198421123 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340738_medium.jpg?v=1611183981&vid=16847198486659 ;;;; variantId6:34322512281731 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340737_medium.jpg?v=1611183964&vid=16847195308163 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340738_medium.jpg?v=1611183981&vid=16847198486659 ;;;; variantId4:34322504679555 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340737_medium.jpg?v=1611183964&vid=16847195308163 ;;;; variantId5:34322507202691 ;;;; variantId2:34322497699971 ;;;; variantId3:34322502418563 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340736_medium.jpg?v=1611184271&vid=16847228141699 ;;;; variantId1:34322494455939 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2020-new-brand-paris-fashion-vetements-air-transport-dhl-hoodies-men-sweatshirts-men-and-women-sweatshirt-tops-letter-yellow-073\",\n                    \"size\": \"XXL\",\n                    \"name\": \"New Brand Paris Fashion Air Transport Dhl Hoodies Men Sweatshirts Men And Women Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: LIZHENDANZHE Sleeve Length(cm): Full Gender: MEN Style: Ca\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Women\",\n                    \"color\": \"White\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754331779\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"95.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322490818691\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"sku\": \"42882418-white-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"95.0\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor3:Black ;;;; variantColor2:White ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor5:Black ;;;; variantColor4:White ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor6:White ;;;; variantSwatchImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId6:34322490818691 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId4:34322489901187 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantId5:34322490228867 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId2:34322489016451 ;;;; variantId3:34322489409667 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantId1:34322488262787 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/private-butterfly-backpack-printed-casual-cut-white-unisex-sweatshirt-two-color-option\",\n                    \"name\": \"Private Butterfly Backpack Printed Casual Cut Unisex Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:women]]>; ;;;; Origin: TR(Origin) Item Type: Hoodies Material: Cotton Gender: WOMEN\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Red-4\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753545347\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"32.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=34322460901507,34322461393027,34322461884547,34322462343299,34322462933123,34322470862979,34322471321731,34322471714947,34322472140931,34322472566915\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322471321731\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110671_medium.jpg?v=1611184197&vid=34322484166787,34322484494467,34322484625539,34322484756611,34322484920451,34322485051523,34322485182595,34322485313667,34322485411971,34322485543043\",\n                    \"sku\": \"42346497-red-4-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.6\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=34322460901507,34322461393027,34322461884547,34322462343299,34322462933123,34322470862979,34322471321731,34322471714947,34322472140931,34322472566915\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.0\",\n                    \"swatchesInfo\": \"variantColor1:Red-5 ;;;; variantColor3:Red-5 ;;;; variantColor2:Red-4 ;;;; variantColor5:Red-2 ;;;; variantColor4:Red-3 ;;;; variantColor6:Red-4 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=16847224569987 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110679_medium.jpg?v=1611184197&vid=16847184625795 ;;;; variantId6:34322470862979 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=16847224569987 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110678_medium.jpg?v=1611184234&vid=16847220736131 ;;;; variantId4:34322466865283 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110682_medium.jpg?v=1611184253&vid=16847224373379 ;;;; variantId5:34322470436995 ;;;; variantId2:34322460901507 ;;;; variantId3:34322463424643 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110679_medium.jpg?v=1611184197&vid=16847184625795 ;;;; variantId1:34322459394179 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/maidangdi-oversized-hoodie-loose-cotton-solid-color-sweatshirt-comfortable-leisure-furniture-outdoor-pullover-chinese-red-hoodie\",\n                    \"size\": \"XL\",\n                    \"name\": \"Oversized Hoodie Loose Cotton Solid Sweatshirt Outdoor Pullover Chinese Hoodie\",\n                    \"shortDesc\": \"closure:closure:none; ;;;; Brand Name: MaiDangDi Origin: CN(Origin) Sleeve Length(cm): Full Style: Casual\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black 11\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192758067331\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"28.48\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152420_medium.jpg?v=1611184222&vid=34322639552643,34322639585411,34322639618179,34322639650947,34322639945859,34322639978627\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322639618179\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152414_medium.jpg?v=1611184222\",\n                    \"sku\": \"39828275-black-11-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.98\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152420_medium.jpg?v=1611184222&vid=34322639552643,34322639585411,34322639618179,34322639650947,34322639945859,34322639978627\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"28.48\",\n                    \"swatchesInfo\": \"variantColor1:Black 13 ;;;; variantColor3:Black 13 ;;;; variantColor2:Gary ;;;; variantColor5:Gary ;;;; variantColor4:Red ;;;; variantColor6:Red ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152402_medium.jpg?v=1611184222&vid=16847187804291 ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152422_medium.jpg?v=1611184222&vid=16847197700227 ;;;; variantId6:34322637193347 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152403_medium.jpg?v=1611184222&vid=16847191638147 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152403_medium.jpg?v=1611184222&vid=16847191638147 ;;;; variantId4:34322636505219 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152402_medium.jpg?v=1611184222&vid=16847187804291 ;;;; variantId5:34322636963971 ;;;; variantId2:34322635456643 ;;;; variantId3:34322636046467 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152422_medium.jpg?v=1611184222&vid=16847197700227 ;;;; variantId1:34322635227267 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/kawaii-hunter-x-hunter-hoodies-men-women-short-sleeve-sweatshirt-killua-zoldyck-anime-manga-black-hoodies-bluzy-tops-clothes\",\n                    \"size\": \"L\",\n                    \"name\": \"Short Sleeve Sweatshirt\",\n                    \"shortDesc\": \"closure:closure:none; ;;;; Brand Name: Dshztooma Origin: CN(Origin) Sleeve Length(cm): Full Style: Casual\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsAlsoViewed\",\n      \"typeOfRequest\": \"RECS_ALSO_VIEWED\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322682183811\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsAlsoViewed\",\n      \"typeOfRequest\": \"RECS_ALSO_VIEWED\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322682183811\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"recsAlsoViewed\",\"typeOfRequest\":\"RECS_ALSO_VIEWED\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322682183811}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"recsAlsoViewed\\\",\\n      \\\"typeOfRequest\\\": \\\"RECS_ALSO_VIEWED\\\",\\n      \\\"settings\\\": {\\n        \\\"context\\\": {\\n          \\\"recentObjects\\\": [\\n            {\\n              \\\"typeOfRecord\\\": \\\"KLEVU_PRODUCT\\\",\\n              \\\"records\\\": [\\n                {\\n                  \\\"id\\\": 34322682183811\\n                }\\n              ]\\n            }\\n          ]\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-158755634955912036\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"recsAlsoViewed\",\"typeOfRequest\":\"RECS_ALSO_VIEWED\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322682183811}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "The end-point is used for retrieving customers also viewed product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "customers-also-viewed-product-recommendations",
  "legacyHash": "ZJoyEAuoUgKMf7wpUI4Ua"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=alsoViewed&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Recently Viewed
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any products which the customer has recently viewed. The most common placements for this banner type are:

**Homepage: Recently Viewed By You**
Show a recommendation banner with products the current customer has recently viewed.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Recently Viewed Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify SEARCH."
      },
      {
        "kind": "required",
        "name": "customANDQuery",
        "type": "String",
        "description": "Here we make a custom query to Klevu, since we know exactly which records we expect in the response. Specify the IDs of all of the products your customer has recently viewed, separated by OR"
      },
      {
        "kind": "optional",
        "name": "topIds",
        "type": "Array",
        "description": "Use this field to specify the order the results should be returned, with the most recently viewed product coming first."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 5,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsRecentlyViewed\",\n            \"meta\": {\n                \"qTime\": 3,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 2,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"color\": \"White Hoodie thick\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753152131\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"56.68\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=34322452512899,34322452971651,34322453430403,34322471256195,34322471551107,34322471846019,34322472173699\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322453430403\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797422_medium.jpg?v=1611184206&vid=34322466177155,34322466603139,34322466930819,34322467192963,34322467586179,34322467946627,34322468339843\",\n                    \"sku\": \"30504298-white-hoodie-thick-asian-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"basePrice\": \"56.68\",\n                    \"startPrice\": \"48.48\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=34322452512899,34322452971651,34322453430403,34322471256195,34322471551107,34322471846019,34322472173699\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"56.68\",\n                    \"swatchesInfo\": \"variantColor1:Black Hoodie thin ;;;; variantColor3:Blue Hoodie thick ;;;; variantColor2:White Hoodie thick ;;;; variantColor5:White Hoodie thin ;;;; variantColor4:Black Hoodie thick ;;;; variantColor6:Yellow Hoodie thin ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=16847225487491 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797419_medium.jpg?v=1611184206&vid=16847185313923 ;;;; variantId6:34322463555715 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=16847185510531 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=16847190851715 ;;;; variantId4:34322456838275 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797418_medium.jpg?v=1611184250&vid=16847223521411 ;;;; variantId5:34322460016771 ;;;; variantId2:34322452512899 ;;;; variantId3:34322453889155 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797425_medium.jpg?v=1611184240&vid=16847221883011 ;;;; variantId1:34322448646275 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-hoodies-men-women-2021-spring-sweatshirt-male-japanese-streetwear-oversized-yellow-anime-hoodie-men-sweatshirts\",\n                    \"size\": \"Asian-M\",\n                    \"name\": \"Singleroad Men's Hoodies Men Women 2021 Sweatshirt Male Japanese Streetwear Oversized Anime Hoodie Men Sweatshirts\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192749842563\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322423840899\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882422-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"basePrice\": \"50.0\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-printed-hooded-oversize-knitted-sweatshirt\",\n                    \"name\": \"WoMen's Printed Hooded Oversize Knitted Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsRecentlyViewed\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\":\"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsRecentlyViewed\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\":\"(id:\\\\\"34322453430403\\\\\" OR id:\\\\\"34322423840899\\\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "// WARNING: For POST requests, body is set to null by browsers.\nvar data = JSON.stringify({\n  \"recordQueries\": [\n    {\n      \"id\": \"recsRecentlyViewed\",\n      \"typeOfRequest\": \"SEARCH\",\n      \"settings\": {\n        \"customANDQuery\": \"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n        \"topIds\": [\n          {\n            \"key\": \"id\",\n            \"value\": \"34322453430403\"\n          },\n          {\n            \"key\": \"id\",\n            \"value\": \"34322423840899\"\n          }\n        ],\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = true;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\r\\n  \\\"recordQueries\\\": [\\r\\n    {\\r\\n      \\\"id\\\": \\\"recsRecentlyViewed\\\",\\r\\n      \\\"typeOfRequest\\\": \\\"SEARCH\\\",\\r\\n      \\\"settings\\\": {\\r\\n        \\\"customANDQuery\\\":\\\"(id:\\\\\\\"34322453430403\\\\\\\" OR id:\\\\\\\"34322423840899\\\\\\\")\\\",\\r\\n        \\\"topIds\\\": [\\r\\n          {\\r\\n            \\\"key\\\": \\\"id\\\",\\r\\n            \\\"value\\\": \\\"34322453430403\\\"\\r\\n          },\\r\\n          {\\r\\n            \\\"key\\\": \\\"id\\\",\\r\\n            \\\"value\\\": \\\"34322423840899\\\"\\r\\n          }\\r\\n        ],\\r\\n        \\\"typeOfRecords\\\": [\\r\\n          \\\"KLEVU_PRODUCT\\\"\\r\\n        ]\\r\\n      }\\r\\n    }\\r\\n  ],\\r\\n  \\\"context\\\": {\\r\\n    \\\"apiKeys\\\": [\\r\\n      \\\"klevu-158755634955912036\\\"\\r\\n    ]\\r\\n  }\\r\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    \"recordQueries\": [\n      {\n        \"id\": \"recsRecentlyViewed\",\n        \"typeOfRequest\": \"SEARCH\",\n        \"settings\": {\n          \"customANDQuery\": \"(id:\\\"34322453430403\\\" OR id:\\\"34322423840899\\\")\",\n          \"topIds\": [\n            {\n              \"key\": \"id\",\n              \"value\": \"34322453430403\"\n            },\n            {\n              \"key\": \"id\",\n              \"value\": \"34322423840899\"\n            }\n          ],\n          \"typeOfRecords\": [\n            \"KLEVU_PRODUCT\"\n          ]\n        }\n      }\n    ],\n    \"context\": {\n      \"apiKeys\": [\n        \"klevu-158755634955912036\"\n      ]\n    }\n  })\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "8Yg33Te4JzfoWp5yEbmJh"
  },
  "description": "The end-point is used for retrieving recently viewed product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "recently-viewed-product-recommendations",
  "legacyHash": "O476dp1jmzIGO8VibBKHx"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=recentlyViewed&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] A/B Test
[path] Guide/Smart Category Merchandising/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can also power your category pages using A/B Testing. This means that for a given Test and Variant combination, the products for a given category are retrieved using the Visual Merchandising rules configured for that A/B Test and Variant.

## Allocating Variants to Store Categories

Klevu allocates for each Category, an A/B Test and a Variant with their IDs. For Category Merchandising, the type will always be “CAT\_NAV”.

Our recommendation is that this request be polled at an interval between 20 minutes and 1 hour, to get either new allocations or skewed allocations of Variants to Categories that were not yet clicked by a shop customer.

As long as an A/B Test ID is received as a Response on this call, said A/B Test is considered Active. Once an ID is no longer received in the Response of this call, it should be removed from the local browser storage.

For each assignment, the distribution of Variants can be different for the same A/B Test ID and Categories. If a Category with an A/B Test Variant ID is selected and viewed by a Shop Customer, that state of having been visited should be recorded, and once another Variant ID is received on the Response for a visited Category, it should be ignored. If a Variant ID is received for a Category that has not yet been visited by a Shop Customer, that Variant ID can be assigned to the Category and it can overwrite any already-existing values in the local browser storage.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/",
  "name": "Retrieve all possible A/B test allocation variants",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "w1fWy9MoWmWlHQkZ_JsR4",
        "code": "{\n    \"assigned\": [\n        {\n            \"sourceId\": \"womens;jeans\",\n            \"abTestId\": \"101\",\n            \"abTestVariantId\": \"aaa\", \n            \"type\": \"CAT_NAV\"\n        },\n        {\n            \"sourceId\": \"womens;shirts\",\n            \"abTestId\": \"101\",\n            \"abTestVariantId\": \"bbb\", \n            \"type\": \"CAT_NAV\"\n        },\n        {\n            \"sourceId\": \"mens;hoodies\",\n            \"abTestId\": \"101\",\n            \"abTestVariantId\": \"aaa\", \n            \"type\": \"CAT_NAV\"\n        },\n        {\n            \"sourceId\": \"kids;toys\",\n            \"abTestId\": \"202\",\n            \"abTestVariantId\": \"xyz\", \n            \"type\": \"CAT_NAV\"\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "w1fWy9MoWmWlHQkZ_JsR4"
  },
  "examples": {
    "languages": [
      {
        "id": "1KknGPRJw2qWs1a3iujb2",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "zL-4m-0P-ibcbzKAg-Vz6",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"text/plain\");\nRequestBody body = RequestBody.create(mediaType, \"\");\nRequest request = new Request.Builder()\n  .url(\"https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/\")\n  .method(\"POST\", body)\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "oS3wyEpfh_rZVdo7tvJK0",
        "code": "curl --location --request POST 'https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/' \\\n--header 'Accept: application/json'",
        "language": "curl",
        "customLabel": ""
      },
      {
        "id": "Wdc7hoEkUM1bDpSS0O32Z",
        "code": "var request = require('request');\nvar options = {\n   'method': 'POST',\n   'url': 'https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/',\n   'headers': {\n      'Accept': 'application/json'\n   }\n};\nrequest(options, function (error, response) {\n   if (error) throw new Error(error);\n   console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "9TSGhG6LfgRBWoAIuFA4U",
        "code": "var myHeaders = new Headers();\nmyHeaders.append(\"Accept\", \"application/json\");\n\nvar requestOptions = {\n   method: 'POST',\n   headers: myHeaders,\n   redirect: 'follow'\n};\n\nfetch(\"https://api.ksearchnet.com/abtest/public/allocation/klevu-158755634955912036/\", requestOptions)\n   .then(response => response.text())\n   .then(result => console.log(result))\n   .catch(error => console.log('error', error));",
        "language": "javascript",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "1KknGPRJw2qWs1a3iujb2"
  },
  "description": "The end-point is used to reteriving available A/B test variants. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "retrieve-all-possible-ab-test-allocation-variants",
  "legacyHash": "uVUu-BrVgpWrXLM-ptkFp"
}
```
:::

## Category Product Search with A/B Test

:::ApiMethodV2
```json
{
  "tab": "request",
  "url": "https://{{Your APIv2 URL}}/cs/v2/search",
  "name": "A/B Test using category merchandising",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "This parameter defines the type of request it is, which should be 'CATNAV' for category merchandising queries. There are other values available, detailed elsewhere in the documentation."
      },
      {
        "kind": "required",
        "name": "categoryPath",
        "type": "String",
        "description": "Specify the name of the category to retrieve results from, in the same case and format as it is indexed with Klevu.\n\nFor nested categories, use the ; character to separate the hierarchy. For example, for 'Mens > Shoes > Trainers and Sneakers' you would specify: Mens;Shoes;Trainers and Sneakers."
      },
      {
        "kind": "required",
        "name": "abTestId",
        "type": "string",
        "description": "The unique identifier of the A/B Test."
      },
      {
        "kind": "required",
        "name": "abTestVariantId",
        "type": "string",
        "description": "The unique identifier of the A/B Test Variant."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 16,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"categoryProducts\",\n            \"meta\": {\n                \"qTime\": 12,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 73,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-156925593843210765\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Hoodies & Sweatshirts\",\n                    \"itemGroupId\": \"4384033833022\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"75.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-red_main_c9193846-bc80-4537-b810-4f6ad82dd6fe_medium.jpg?v=1575478019\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456541246\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ01-S-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-red_main_c9193846-bc80-4537-b810-4f6ad82dd6fe_medium.jpg?v=1575478019\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"75.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets;;Hoodies & Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/stellar-solar-jacket-s-red\",\n                    \"tags\": \"Cold-whether, comfortable, crewneck, Grayson, Hoodie, machine, Sweatshirt, winter, Wool\",\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"shortDesc\": \"Beat the heat and protect yourself from sunrays with the Stellar Solar Jacket. It's loaded with all the engineered features you need for an intense, safe outdoor workout: 100% UV protection, a breathable perforated construction, and advanced moist\",\n                    \"category\": \"Jackets;;Hoodies & Sweatshirts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052215870\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-blue_main_bb248254-73cc-4521-8105-fe2277267348_medium.jpg?v=1575478286\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487441470\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Blue\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-blue_main_bb248254-73cc-4521-8105-fe2277267348_medium.jpg?v=1575478286\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-blue\",\n                    \"tags\": \"blue, machine, royal, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033341502\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-orange_main_098af8fb-1cf2-473f-907a-10922e39beae_medium.jpg?v=1575478007\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455590974\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-Orange\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-orange_main_098af8fb-1cf2-473f-907a-10922e39beae_medium.jpg?v=1575478007\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-orange\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384031244350\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"77.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj06-green_main_30b7fa7f-a3ce-4513-9307-822bf013a89d_medium.jpg?v=1575477963\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366453067838\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ06-XS-Green\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj06-green_main_30b7fa7f-a3ce-4513-9307-822bf013a89d_medium.jpg?v=1575477963\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"77.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/juno-jacket-green\",\n                    \"tags\": \"adjustable, comfort, machine, royal, running, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Juno Jacket\",\n                    \"shortDesc\": \"On colder-than-comfortable mornings, you'll love warming up in the Juno All-Ways Performanc Jacket, designed to compete with wind and chill. Built-in Cocona® technology aids evaporation, while a special zip placket and stand-up collar keep your ne\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052084798\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-green_main_7f692ff8-45b0-4d08-8371-a2044df82752_medium.jpg?v=1575478284\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487310398\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Green\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-green_main_7f692ff8-45b0-4d08-8371-a2044df82752_medium.jpg?v=1575478284\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-green\",\n                    \"tags\": \"green, machine, royal, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384051527742\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"66.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj10-red_main_9e1898b9-9d4a-41df-8dc6-7d31cd23c34e_medium.jpg?v=1575478275\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366485966910\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ10-XS-Red\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj10-red_main_9e1898b9-9d4a-41df-8dc6-7d31cd23c34e_medium.jpg?v=1575478275\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"66.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Tops;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/mars-heattech-trade-pullover-red\",\n                    \"tags\": \"machine, red, royal, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Mars HeatTech™ Pullover\",\n                    \"shortDesc\": \"The Mars HeatTech™ Jacket defense against winter climes so you can play offense in the park, on the trail or in the deck chair. Great for the ski lodge or stadium, it features a wind- and water-resistant outer shell with a draw-cord hood and deep\",\n                    \"category\": \"Tops;;Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033603646\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"56.25\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj02-blue_main_8549c057-4567-4b63-ac2e-2068d345ff28_medium.jpg?v=1575478014\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456279102\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ02-XS-Blue\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj02-blue_main_8549c057-4567-4b63-ac2e-2068d345ff28_medium.jpg?v=1575478014\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"56.25\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/josie-yoga-jacket-blue\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Small\",\n                    \"name\": \"Josie Yoga Jacket\",\n                    \"shortDesc\": \"When your near future includes yoga, the cozy comfort of the Josie Yoga Jacket gets your mind and body ready. Stretchy CoolTech™ fabric with zipper pockets makes this jacket the right gear for studio time or teatime after. • Slate rouched n\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052150334\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"99.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-gray_main_3787cf65-8e0a-4540-8f11-6d188980a6eb_medium.jpg?v=1575478285\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487375934\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ08-XS-Gray\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj08-gray_main_3787cf65-8e0a-4540-8f11-6d188980a6eb_medium.jpg?v=1575478285\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"99.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/lando-gym-jacket-gray\",\n                    \"tags\": \"gray, machine, royal, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Lando Gym Jacket\",\n                    \"shortDesc\": \"The Lando Gym Jacket offers strategic ventilation at perspiration-prone areas, while moisture-wicking technology helps you stay dry. Side-seam pockets house your favorite media device, so you're plugged in when working out. • Gray polyester\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033243198\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-white_main_d8fa2b03-08ff-485c-afd1-b3761e70e9ce_medium.jpg?v=1575478004\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455427134\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-White\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-white_main_d8fa2b03-08ff-485c-afd1-b3761e70e9ce_medium.jpg?v=1575478004\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-white\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Medium\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384033308734\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"84.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-red_main_5c76d8d8-ad1a-414f-b6b7-9edccc50b955_medium.jpg?v=1575478005\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366455525438\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ04-XS-Red\",\n                    \"brand\": \"KSD\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj04-red_main_5c76d8d8-ad1a-414f-b6b7-9edccc50b955_medium.jpg?v=1575478005\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/ingrid-running-jacket-red\",\n                    \"tags\": \"comfort, machine, royal, running, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Ingrid Running Jacket\",\n                    \"shortDesc\": \"The Ingrid Running Jacket combines sleek design and high performance with slim, contoured fit and moisture-wicking fabric. It features a full-zip construction and a collared neck to keep the elements out and body heat in. • Slim fit. • Moi\",\n                    \"category\": \"Jackets\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Hoodies & Sweatshirts\",\n                    \"itemGroupId\": \"4384033964094\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"75.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-blue_main_d6ed0a23-7d18-42d4-921c-5669f65a7580_medium.jpg?v=1575478022\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366456672318\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"WJ01-S-Blue\",\n                    \"brand\": \"MNH\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj01-blue_main_d6ed0a23-7d18-42d4-921c-5669f65a7580_medium.jpg?v=1575478022\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"75.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets;;Hoodies & Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/stellar-solar-jacket-s-blue\",\n                    \"tags\": \"Cold-whether, comfortable, crewneck, Grayson, Hoodie, machine, Sweatshirt, winter, Wool\",\n                    \"size\": \"Small\",\n                    \"name\": \"Stellar Solar Jacket\",\n                    \"shortDesc\": \"Beat the heat and protect yourself from sunrays with the Stellar Solar Jacket. It's loaded with all the engineered features you need for an intense, safe outdoor workout: 100% UV protection, a breathable perforated construction, and advanced moist\",\n                    \"category\": \"Jackets;;Hoodies & Sweatshirts\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"type\": \"Jackets\",\n                    \"itemGroupId\": \"4384052412478\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"GBP\",\n                    \"price\": \"72.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj07-red_main_7fb57683-fddb-44a9-90aa-fc03536bbd90_medium.jpg?v=1575478289\",\n                    \"currency\": \"GBP\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"31366487769150\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"MJ07-XS-Red\",\n                    \"brand\": \"KKE\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mj07-red_main_7fb57683-fddb-44a9-90aa-fc03536bbd90_medium.jpg?v=1575478289\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"72.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/orion-two-tone-fitted-jacket-red\",\n                    \"tags\": \"machine, red, royal, zipped\",\n                    \"size\": \"Large\",\n                    \"name\": \"Orion Two-Tone Fitted Jacket\",\n                    \"shortDesc\": \"While you're getting fit, you need a fitted jacket to match. Striking color blocking patterns on hood, shoulders and arms are hallmarks of the Orion Two-Tone Fitted Jacket. They provide eye-catching contrast against the rich, torso tones of this 1\",\n                    \"category\": \"Jackets\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"categoryProducts\",\n      \"typeOfRequest\": \"CATNAV\",\n      \"settings\": {\n         \"query\": {\n           \"categoryPath\": \"Jackets\"\n         },\n         \"abTestId\": \"9c8bm3o1-osjgoqn9-9mbjudid\",\n         \"abTestVariantId\": \"if92kdmc-98ckcj89-98cjcd9d\"\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"categoryProducts\",\n      \"typeOfRequest\": \"CATNAV\",\n      \"settings\": {\n         \"query\": {\n            \"categoryPath\": \"Jackets\"\n         },\n         \"abTestId\": \"9c8bm3o1-osjgoqn9-9mbjudid\",\n         \"abTestVariantId\": \"if92kdmc-98ckcj89-98cjcd9d\"\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"categoryProducts\",\"typeOfRequest\":\"CATNAV\",\"settings\":{\"query\":{\"categoryPath\":\"Jackets\"},\"abTestId\":\"9c8bm3o1-osjgoqn9-9mbjudid\",\"abTestVariantId\":\"if92kdmc-98ckcj89-98cjcd9d\"}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"categoryProducts\\\",\\n      \\\"typeOfRequest\\\": \\\"CATNAV\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"categoryPath\\\": \\\"Jackets\\\"\\n       },\\n       \\\"abTestId\\\": \\\"9c8bm3o1-osjgoqn9-9mbjudid\\\",\\n       \\\"abTestVariantId\\\": \\\"if92kdmc-98ckcj89-98cjcd9d\\\"\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"categoryProducts\",\"typeOfRequest\":\"CATNAV\",\"settings\":{\"query\":{\"categoryPath\":\"Jackets\"},\"abTestId\":\"9c8bm3o1-osjgoqn9-9mbjudid\",\"abTestVariantId\":\"if92kdmc-98ckcj89-98cjcd9d\"}}],\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "jSU7DlYyJ_eUh63YSP682"
  },
  "description": "This is an example how to fetch products from specific A/B test variant.\n\nNote: {{Your APIv2 URL}} can be found in your KMC under 'Store Settings'",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "ab-test-using-category-merchandising",
  "legacyHash": "zRSNwflRcZgvZNZp9OE34"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=AbTest&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Trending Products
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

Klevu can power a recommendation banner showcasing the most popular products in the store. The most common placements for this banner type are:

**Homepage: Trending Products**
Show a recommendation banner with the most popular products across the entire store.

**Homepage: Trending Products For You**
Present the most popular products in the store, tailored to the customer's recent history.

**Category Page: Trending in \{Category}**
Show a banner with the most popular products in the current category. If you already have Klevu powered category product listings, add this banner with personalisation enabled so the customer sees something, different just for them

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Trending Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "string",
        "description": "For this recommendation type, please specify RECS_TRENDING."
      },
      {
        "kind": "optional",
        "name": "enablePersonalisation",
        "type": "Boolean",
        "description": "Whether or not you would like to personalise the recommendation results. "
      },
      {
        "kind": "optional",
        "name": "recentObjects",
        "type": "Object",
        "description": "The IDs of any products the customer recently clicked on, to be used in conjunction with enablePersonalisation."
      },
      {
        "kind": "optional",
        "name": "categoryPath",
        "type": "string",
        "description": "This is only required when you want to give Category-specific context to a recommendation query. Specify the name of the category to retrieve results from, in the same case and format as it is indexed with Klevu.\n\nFor nested categories, use the ; character to separate the hierarchy. For example, for 'Mens > Shoes > Trainers and Sneakers' you would specify: Mens;Shoes;Trainers and Sneakers."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "cFqj2aSh0yGaWKGLQWFjm",
        "code": "{\n    \"meta\": {\n        \"qTime\": 65,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsTrending\",\n            \"meta\": {\n                \"qTime\": 18,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 34,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": true,\n                \"idsUsedForPersonalisation\": [\n                    \"34322416828547\",\n                    \"34322607374467\",\n                    \"34322404245635\",\n                    \"34322662686851\",\n                    \"34322403950723\",\n                    \"34322464309379\"\n                ]\n            },\n            \"records\": [\n                {\n                    \"color\": \"Yellow\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757248131\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"26.44\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457424_medium.jpg?v=1611184383&vid=34322606719107,34322607374467,34322607734915,34322608160899,34322608423043\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322607374467\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457422_medium.jpg?v=1611184221&vid=34322617532547,34322621825155,34322622087299,34322622414979,34322622742659\",\n                    \"sku\": \"41313874-yellow-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"24.98\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457424_medium.jpg?v=1611184383&vid=34322606719107,34322607374467,34322607734915,34322608160899,34322608423043\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"26.44\",\n                    \"swatchesInfo\": \"variantColor1:Yellow ;;;; variantColor3:Yellow ;;;; variantColor2:Green ;;;; variantColor5:Green ;;;; variantColor4:Rice white ;;;; variantColor6:Dark Grey ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457410_medium.jpg?v=1611184359&vid=16847232663683 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457424_medium.jpg?v=1611184383&vid=16847236530307 ;;;; variantId6:34322611634307 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457411_medium.jpg?v=1611184221&vid=16847196782723 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457411_medium.jpg?v=1611184221&vid=16847196782723 ;;;; variantId4:34322608717955 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457408_medium.jpg?v=1611184221&vid=16847201501315 ;;;; variantId5:34322610126979 ;;;; variantId2:34322607014019 ;;;; variantId3:34322607374467 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1601457424_medium.jpg?v=1611184383&vid=16847236530307 ;;;; variantId1:34322606719107 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 59,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/turtleneck-men-sweater-christmas-cotton-male-sweater-winter-pullover-turtle-neck-mens-jumper-white-mens-knitwear-pull-homme\",\n                    \"size\": \"XL\",\n                    \"name\": \"Turtle Neck Men Sweater Christmas Cotton Male Sweater Pullover Turtle Neck Men's Jumper Men's Knitwear Pull\",\n                    \"shortDesc\": \"gender:gender:men; size:size::,M,L,XL,2XL]]>; decoration:decoration:none; closure:closure:none; ;;;; Brand Name: Uyuk Origin: CN(Origin) Pattern Type:\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756985987\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904833192067\",\n                    \"price\": \"48.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717245_medium.jpg?v=1611183920&vid=34322603376771,34322603475075,34322603540611,34322603638915,34322603737219,34322603868291,34322604032131,34322604195971\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322603540611\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717245_medium.jpg?v=1611183920&vid=34322603376771,34322603475075,34322603540611,34322603638915,34322603737219,34322603868291,34322604032131,34322604195971\",\n                    \"sku\": \"22837413-black-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"41.56\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717245_medium.jpg?v=1611183920&vid=34322603376771,34322603475075,34322603540611,34322603638915,34322603737219,34322603868291,34322604032131,34322604195971\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"48.0\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor3:Wine Red ;;;; variantColor2:Blue ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor4:White ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717247_medium.jpg?v=1611184375&vid=16847235055747 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717246_medium.jpg?v=1611183943&vid=16847190589571 ;;;; variantId4:34322609307779 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717248_medium.jpg?v=1611184362&vid=16847232827523 ;;;; variantId2:34322604425347 ;;;; variantId3:34322606555267 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1410717245_medium.jpg?v=1611183920&vid=16847179350147 ;;;; variantId1:34322603376771 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Coats & Jackets;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 31,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/5xl-men-turtleneck-sweater-thick-knitted-pullover-winter-sweater-male-high-turtle-neck-plus-size-mens-coats-black-white-red-4xl\",\n                    \"size\": \"L\",\n                    \"name\": \"Men Turtle Neck Sweater Thick Knitted Pullover Sweater Male High Turtle Neck Plus Size Men's Coats\",\n                    \"shortDesc\": \"gender:gender:men; season:season:2018,autumn,winter,new,arrivals; closure:closure:none; decoration:decoration:ruched; ;;;; Style: Casual Material: Wool Materi\",\n                    \"category\": \"All;;Mens Coats & Jackets;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Blue\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756560003\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904810221699\",\n                    \"price\": \"43.90\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655070_medium.jpg?v=1611184269&vid=34322588991619,34322589319299,34322589548675,34322589778051,34322590367875,34322592497795,34322593022083,34322593284227\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322589548675\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655069_medium.jpg?v=1611184229&vid=34322590040195,34322590662787,34322590924931,34322596954243,34322597314691,34322597609603,34322597970051,34322598199427\",\n                    \"sku\": \"30361222-blue-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655070_medium.jpg?v=1611184269&vid=34322588991619,34322589319299,34322589548675,34322589778051,34322590367875,34322592497795,34322593022083,34322593284227\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"43.9\",\n                    \"swatchesInfo\": \"variantColor1:Blue ;;;; variantColor3:Blue ;;;; variantColor2:Black ;;;; variantColor5:Wine Red ;;;; variantColor4:Black ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor6:Blue ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655070_medium.jpg?v=1611184269&vid=16847227682947 ;;;; variantId6:34322592497795 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655070_medium.jpg?v=1611184269&vid=16847227682947 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655069_medium.jpg?v=1611184229&vid=16847174893699 ;;;; variantId4:34322590662787 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655071_medium.jpg?v=1611184229&vid=16847188721795 ;;;; variantId5:34322591219843 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655069_medium.jpg?v=1611184229&vid=16847174893699 ;;;; variantId2:34322590040195 ;;;; variantId3:34322590367875 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315655070_medium.jpg?v=1611184269&vid=16847227682947 ;;;; variantId1:34322588991619 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 31,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/5xl-plus-size-sweater-men-turtleneck-thick-warm-mens-sweaters-wool-pullover-high-turtle-neck-casual-male-sweter-pull-homme-black\",\n                    \"size\": \"M\",\n                    \"name\": \"Plus Size Sweater Men Turtle Neck Thick Warm Men's Sweaters Wool Pullover High Turtle Neck Casual Male Sweater Pull Black\",\n                    \"shortDesc\": \"season:season:2018,autumn,winter,new,arrivals; decoration:decoration:ruched; closure:closure:none; ;;;; Origin: CN(Origin) Model Number: Mens Turtleneck Sweater\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756822147\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"33.20\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279982_medium.jpg?v=1611183902&vid=34322598494339,34322598658179,34322598756483,34322598854787,34322598985859\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322598854787\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279985_medium.jpg?v=1611183902&vid=34322599116931,34322599215235,34322599280771,34322599411843,34322599542915\",\n                    \"sku\": \"31688107-black-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279982_medium.jpg?v=1611183902&vid=34322598494339,34322598658179,34322598756483,34322598854787,34322598985859\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"33.2\",\n                    \"swatchesInfo\": \"variantColor1:White ;;;; variantColor3:Gray ;;;; variantColor2:Black ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279985_medium.jpg?v=1611183902&vid=16847176073347 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279982_medium.jpg?v=1611183902&vid=16847177711747 ;;;; variantId2:34322598494339 ;;;; variantId3:34322599116931 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1187279991_medium.jpg?v=1611183929&vid=16847187837059 ;;;; variantId1:34322597707907 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 14,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/striped-turtleneck-mens-sweaters-wool-pullover-sweater-male-oversized-turtle-neck-men-sweter-pull-jumper-korean-style-white\",\n                    \"size\": \"L\",\n                    \"name\": \"Striped Turtle Neck Men's Sweaters Wool Pullover Sweater Male Oversized Turtle Neck Men Sweater Pull Jumper Korean Style\",\n                    \"shortDesc\": \"gender:gender:men,men; decoration:decoration:none; closure:closure:none; ;;;; Origin: CN(Origin) Model Number: mens sweaters wool pullover Pattern Type:\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Yellow\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759083139\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904886505603\",\n                    \"price\": \"49.98\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368407_medium.jpg?v=1611183999&vid=34322659049603,34322659934339,34322661802115,34322662686851\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322662686851\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368401_medium.jpg?v=1611183924&vid=34322651578499,34322652463235,34322657149059,34322658033795\",\n                    \"sku\": \"41022628-yellow-asian-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"49.98\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368407_medium.jpg?v=1611183999&vid=34322659049603,34322659934339,34322661802115,34322662686851\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"49.98\",\n                    \"swatchesInfo\": \"variantColor1:Blue ;;;; variantColor3:Blue ;;;; variantColor2:Navy Blue ;;;; variantColor5:Navy Blue ;;;; variantColor4:Black ;;;; variantColor6:Gray ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368403_medium.jpg?v=1611183946&vid=16847191179395 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368402_medium.jpg?v=1611184384&vid=16847237251203 ;;;; variantId6:34322655150211 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368408_medium.jpg?v=1611183992&vid=16847200583811 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368408_medium.jpg?v=1611183992&vid=16847200583811 ;;;; variantId4:34322651578499 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368401_medium.jpg?v=1611183924&vid=16847186821251 ;;;; variantId5:34322653315203 ;;;; variantId2:34322648531075 ;;;; variantId3:34322650103939 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646368402_medium.jpg?v=1611184384&vid=16847237251203 ;;;; variantId1:34322646859907 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 35,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/man-pullovers-hoodies-jesus-is-king-kanye-west-vintage-autumn-winter-blue-hip-hop-fleece-hoodies-urban-streetwear-hoody-women\",\n                    \"size\": \"Asian XL\",\n                    \"name\": \"Man Pullovers Hoodies\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: HANGJIA Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"dark green2\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753610883\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"23.58\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462192_medium.jpg?v=1611184202&vid=34322483380355,34322483478659,34322483609731,34322483740803,34322483871875,34322483970179\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322483740803\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462192_medium.jpg?v=1611184202&vid=34322483380355,34322483478659,34322483609731,34322483740803,34322483871875,34322483970179\",\n                    \"sku\": \"42716014-dark-green2-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462192_medium.jpg?v=1611184202&vid=34322483380355,34322483478659,34322483609731,34322483740803,34322483871875,34322483970179\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"23.58\",\n                    \"swatchesInfo\": \"variantColor1:khaki1 ;;;; variantColor3:orange1 ;;;; variantColor2:yellow1 ;;;; variantColor5:purple1 ;;;; variantColor4:dark green1 ;;;; variantColor6:pink1 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462183_medium.jpg?v=1611184259&vid=16847225880707 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462180_medium.jpg?v=1611184260&vid=16847226011779 ;;;; variantId6:34322470600835 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462179_medium.jpg?v=1611184258&vid=16847225421955 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462182_medium.jpg?v=1611184202&vid=16847175647363 ;;;; variantId4:34322466013315 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462181_medium.jpg?v=1611184256&vid=16847225028739 ;;;; variantId5:34322468438147 ;;;; variantId2:34322460278915 ;;;; variantId3:34322463260803 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462178_medium.jpg?v=1611184202&vid=16847183184003 ;;;; variantId1:34322456903811 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/couple-lovers-sweatshirts-pullover-men-women-fashion-smiley-face-printed-purple-green-justin-bieber-hoodie\",\n                    \"size\": \"XL\",\n                    \"name\": \"Couple Lovers Sweatshirts Pullover Men Women Fashion Smiley Face Printed Justin Bieber Hoodie\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: MEUGLEMENT Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"3D 7\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192755380355\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"26.96\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=34322535940227,34322539380867,34322540527747,34322541838467,34322542952579,34322544001155,34322545180803,34322546065539,34322546983043\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322539380867\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801482_medium.jpg?v=1611183908&vid=34322582929539,34322583257219,34322583584899,34322583912579,34322584273027,34322584666243,34322585026691,34322585452675\",\n                    \"sku\": \"37091373-3d-7-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"26.36\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=34322535940227,34322539380867,34322540527747,34322541838467,34322542952579,34322544001155,34322545180803,34322546065539,34322546983043\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"26.96\",\n                    \"swatchesInfo\": \"variantColor1:3D ;;;; variantColor3:3D 12 ;;;; variantColor2:3D 11 ;;;; variantColor5:3D 6 ;;;; variantColor4:3D 7 ;;;; variantColor6:3D 7 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=16847231680643 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801489_medium.jpg?v=1611183980&vid=16847198191747 ;;;; variantId6:34322539380867 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801488_medium.jpg?v=1611184375&vid=16847234957443 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801483_medium.jpg?v=1611184373&vid=16847233941635 ;;;; variantId4:34322535940227 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=16847231680643 ;;;; variantId5:34322537087107 ;;;; variantId2:34322517295235 ;;;; variantId3:34322525290627 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801478_medium.jpg?v=1611184383&vid=16847236628611 ;;;; variantId1:34322506481795 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/3d-printed-hoodies-one-piece-hoodie-men-sweatshirt-women-harajuku-pullovers-casual-hot-sale-anime-black-3d-hoodies-clothes\",\n                    \"size\": \"XL\",\n                    \"name\": \"3D Printed Hoodies One Piece Hoodie Men Sweatshirt Women Harajuku Pullovers Casual Hot Sale Anime 3D Hoodies Clothes\",\n                    \"shortDesc\": \"gender:gender:men,men; closure:closure:none; ;;;; Brand Name: Rholycrown Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Dark Grey\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756756611\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"27.86\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1234576748_medium.jpg?v=1611183946&vid=34322598068355,34322598297731,34322598396035,34322598527107,34322598625411\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322598068355\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1234576748_medium.jpg?v=1611183946&vid=34322598068355,34322598297731,34322598396035,34322598527107,34322598625411\",\n                    \"sku\": \"21550359-dark-grey-s\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.86\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1234576748_medium.jpg?v=1611183946&vid=34322598068355,34322598297731,34322598396035,34322598527107,34322598625411\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"27.86\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor2:Dark Grey ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1234576748_medium.jpg?v=1611183946&vid=16847191343235 ;;;; variantId2:34322598068355 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1234576747_medium.jpg?v=1611183967&vid=16847195701379 ;;;; variantId1:34322596528259 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 9,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2019-autumn-mens-sweater-pullover-male-long-sleeve-horn-button-knitted-turtleneck-sweaters-slim-fit-black-gray-pullovers-s-2xl\",\n                    \"size\": \"S\",\n                    \"name\": \"Men's Sweater Pullover Male Long Sleeve Horn Button Knitted Turtle Neck Sweaters Slim Fit Pullovers\",\n                    \"shortDesc\": \"gender:gender:men; decoration:decoration:button; closure:closure:none; ;;;; Brand Name: VEAKER Model Number: Men's Sweater Pullover Pattern Type: Sol\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Army Green\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757280899\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"84.98\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665268494_medium.jpg?v=1611184350&vid=34322606162051,34322606424195,34322606653571,34322606948483\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322606162051\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665268493_medium.jpg?v=1611184220&vid=34322607243395,34322607571075,34322607931523,34322608193667\",\n                    \"sku\": \"42883420-army-green-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665268494_medium.jpg?v=1611184350&vid=34322606162051,34322606424195,34322606653571,34322606948483\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"84.98\",\n                    \"swatchesInfo\": \"variantColor1:Army Green ;;;; variantColor2:Black ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665268493_medium.jpg?v=1611184220&vid=16847188656259 ;;;; variantId2:34322607571075 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665268494_medium.jpg?v=1611184350&vid=16847232237699 ;;;; variantId1:34322606162051 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 7,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2020-new-mens-vintage-warm-soft-mohair-turtleneck-sweater-green-grey-long-sleeve-sweater-with-elbow-patch\",\n                    \"size\": \"XL\",\n                    \"name\": \"New Men's Vintage Warm Soft Mohair Turtle Neck Sweater Long Sleeve Sweater With Elbow Patch\",\n                    \"shortDesc\": \"gender:gender:men]]>; decoration:decoration:patch designs; closure:closure:none; ;;;; Model Number: S1901294 Pattern Type: Solid Collar: Turtleneck\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Green\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756723843\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"40.78\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897966_medium.jpg?v=1611184350&vid=34322594889859,34322595414147,34322595741827,34322596003971,34322596266115,34322596495491\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322596266115\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897965_medium.jpg?v=1611184339&vid=34322595184771,34322596692099,34322596921475,34322597216387,34322597576835,34322597904515\",\n                    \"sku\": \"32126090-green-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"38.38\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897966_medium.jpg?v=1611184350&vid=34322594889859,34322595414147,34322595741827,34322596003971,34322596266115,34322596495491\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"40.78\",\n                    \"swatchesInfo\": \"variantColor1:Green ;;;; variantColor3:Green ;;;; variantColor2:navy blue ;;;; variantColor4:navy blue ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897966_medium.jpg?v=1611184350&vid=16847232204931 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897965_medium.jpg?v=1611184339&vid=16847231778947 ;;;; variantId4:34322596692099 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897965_medium.jpg?v=1611184339&vid=16847231778947 ;;;; variantId2:34322595184771 ;;;; variantId3:34322595414147 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1429897966_medium.jpg?v=1611184350&vid=16847232204931 ;;;; variantId1:34322594889859 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 11,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2019-new-mens-long-hooded-cardigan-sweater-male-autumn-black-green-cardigan-coat-casual-solid-color-sweaters-outerwear-s-3xl\",\n                    \"size\": \"XL\",\n                    \"name\": \"New Men's Long Hooded Cardigan Sweater Male Cardigan Coat Casual Solid Sweaters Outerwear\",\n                    \"shortDesc\": \"decoration:decoration:none; closure:closure:none; ;;;; Brand Name: VEAKER Model Number: Long Hooded Cardigan Sweater Pattern Type: Solid\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Green\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759935107\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"71.30\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1508496603_medium.jpg?v=1611184254&vid=34322685100163,34322685427843,34322685853827,34322686279811\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322685427843\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1508496603_medium.jpg?v=1611184254&vid=34322685100163,34322685427843,34322685853827,34322686279811\",\n                    \"sku\": \"34699888-green-s\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1508496603_medium.jpg?v=1611184254&vid=34322685100163,34322685427843,34322685853827,34322686279811\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"71.3\",\n                    \"swatchesInfo\": \"variantColor1:Green ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1508496603_medium.jpg?v=1611184254&vid=16847185936515 ;;;; variantId1:34322685100163 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Coats & Jackets;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 3,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/madden-male-hooded-pullover-long-sleeve-deck-parker-jacket-drawstring-neckline-workwear-jacket-green-cuffs-ribbon-closure-jacket\",\n                    \"size\": \"S\",\n                    \"name\": \"Madden Male Hooded Pullover Long Sleeve Deck Parker Jacket\",\n                    \"shortDesc\": \"gender:gender:men; size:size:100%,COTTON; closure:closure:none; ;;;; Brand Name: MADEN Origin: CN(Origin) Sleeve Length(cm): Full\",\n                    \"category\": \"All;;Mens Coats & Jackets;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Light Grey\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757313667\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"35.18\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970384_medium.jpg?v=1611183941&vid=34322611273859,34322611667075,34322611961987,34322612191363,34322612387971\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322611667075\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970383_medium.jpg?v=1611183861&vid=34322609406083,34322609832067,34322610159747,34322610487427,34322610913411\",\n                    \"sku\": \"6855204-light-grey-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970384_medium.jpg?v=1611183941&vid=34322611273859,34322611667075,34322611961987,34322612191363,34322612387971\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"35.18\",\n                    \"swatchesInfo\": \"variantColor1:Middle Grey ;;;; variantColor3:Light Grey ;;;; variantColor2:Dark Grey ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970384_medium.jpg?v=1611183941&vid=16847190032515 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970383_medium.jpg?v=1611183861&vid=16847175614595 ;;;; variantId2:34322609406083 ;;;; variantId3:34322611273859 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-303970382_medium.jpg?v=1611184312&vid=16847230238851 ;;;; variantId1:34322607669379 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 14,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2016-latest-style-fashion-grey-v-neck-sleeveless-knitting-pattern-mens-cable-sweater-vest\",\n                    \"size\": \"M\",\n                    \"name\": \"Latest Style Fashion V Neck Sleeveless Knitting Pattern Men's Cable Sweater Vest\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; decoration:decoration:none; ;;;; Brand Name: NoEnName_Null Gender: MEN Technics: Flat Knitted\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "cFqj2aSh0yGaWKGLQWFjm"
  },
  "examples": {
    "languages": [
      {
        "id": "7KLhLHdZbutlUjSSGnS_H",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsTrending\",\n      \"typeOfRequest\": \"RECS_TRENDING\",\n      \"settings\": {\n        \"query\": {\n          \"categoryPath\": \"Jackets\"\n        },\n        \"personalisation\": {\n          \"enablePersonalisation\": true\n        },\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": \"34322416828547\"\n                },\n                {\n                  \"id\": \"34322607374467\"\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "none",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "qLTPosCUINKC3gQawRdvM",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsTrending\",\n      \"typeOfRequest\": \"RECS_TRENDING\",\n      \"settings\": {\n        \"query\": {\n          \"categoryPath\": \"Mens Sweaters\"\n        },\n        \"personalisation\": {\n          \"enablePersonalisation\": true\n        },\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": \"34322416828547\"\n                },\n                {\n                  \"id\": \"34322607374467\"\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "ptBHWNwsQoV4Yk3yKMbyL",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"recsTrending\",\"typeOfRequest\":\"RECS_TRENDING\",\"settings\":{\"query\":{\"categoryPath\":\"Mens Sweaters\"},\"personalisation\":{\"enablePersonalisation\":true},\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":\"34322416828547\"},{\"id\":\"34322607374467\"}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "b9GUcOLzvVfAw5P3LLMTJ",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"recsTrending\\\",\\n      \\\"typeOfRequest\\\": \\\"RECS_TRENDING\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"categoryPath\\\": \\\"Mens Sweaters\\\"\\n        },\\n        \\\"personalisation\\\": {\\n          \\\"enablePersonalisation\\\": true\\n        },\\n        \\\"context\\\": {\\n          \\\"recentObjects\\\": [\\n            {\\n              \\\"typeOfRecord\\\": \\\"KLEVU_PRODUCT\\\",\\n              \\\"records\\\": [\\n                {\\n                  \\\"id\\\": \\\"34322416828547\\\"\\n                },\\n                {\\n                  \\\"id\\\": \\\"34322607374467\\\"\\n                }\\n              ]\\n            }\\n          ]\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-158755634955912036\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "ZTP2accUgnh6yKGyvjemZ",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"recsTrending\",\"typeOfRequest\":\"RECS_TRENDING\",\"settings\":{\"query\":{\"categoryPath\":\"Mens Sweaters\"},\"personalisation\":{\"enablePersonalisation\":true},\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":\"34322416828547\"},{\"id\":\"34322607374467\"}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ptBHWNwsQoV4Yk3yKMbyL"
  },
  "description": "The end-point is used for retrieving trending products.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "trending-product-recommendations",
  "legacyHash": "7_M-H9yYaqOOl-DDvdsmt"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=trendingProducts&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Search Events
[path] Guide/Analytics Tracking/



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/n-search/search",
  "name": "Reporting Product Searches",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "klevu_apiKey",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "klevu_term",
        "type": "string",
        "description": "This is the term being searched. For example: iphone 5s.\n\n*For tracking of a facet click, append the selected facet to the term.\ne.g  iphone 5s [[color:black]]"
      },
      {
        "kind": "required",
        "name": "klevu_totalResults",
        "type": "string",
        "description": "This is the total number of results returned for the searched term. It must be an integer (e.g. 5)"
      },
      {
        "kind": "required",
        "name": "klevu_typeOfQuery",
        "type": "string",
        "description": "When you receive a response for a search query, look at the value of the typeOfQuery element under the metaData section (e.g. WILDCARD_AND, FUZZY_AND). You need to pass this value to this parameter."
      },
      {
        "kind": "required",
        "name": "klevu_shopperIP",
        "type": "string",
        "description": "IP address of the shopper who searched a term. \n\n*If calling from javascript (i.e. an ajax call), this is an optional parameter."
      },
      {
        "name": "klevu_shopperIP_v4",
        "kind": "optional",
        "type": "string",
        "description": "IPv4 address of the shopper who searched a term. \n",
        "children": []
      },
      {
        "name": "klevu_shopperIP_v6",
        "kind": "optional",
        "type": "string",
        "description": "IPv6 address of the shopper who searched a term. ",
        "children": []
      },
      {
        "name": "data_protection",
        "kind": "optional",
        "type": "Boolean",
        "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true.",
        "children": []
      },
      {
        "name": "klevu_uuid",
        "kind": "optional",
        "type": "string",
        "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid",
        "children": []
      },
      {
        "name": "klevu_country",
        "kind": "optional",
        "type": "string",
        "description": "2-digit country code of the shopper who searched a term. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes",
        "children": []
      },
      {
        "name": "klevu_city",
        "kind": "optional",
        "type": "string",
        "description": "City name of the shopper who searched a term.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "ewnRZCOKsK8s4PdjFvhyM",
        "code": "curl --location --request GET 'https://stats.ksearchnet.com/analytics/n-search/search?apiKey=klevu-1234567890&term=red%20shoes&klevu_totalResults=35&klevu_typeOfQuery=WILDCARD_AND'",
        "language": "curl",
        "customLabel": ""
      },
      {
        "id": "EQqDeUhwCKDCWovOoWPGC",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://stats.ksearchnet.com/analytics/n-search/search?apiKey=klevu-1234567890&term=red%20shoes&klevu_totalResults=35&klevu_typeOfQuery=WILDCARD_AND',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "8jgVxehuUIB8HJb3WWGYb",
        "code": "var requestOptions = {\n  method: 'GET',\n  redirect: 'follow'\n};\n\nfetch(\"https://stats.ksearchnet.com/analytics/n-search/search?klevu_apiKey=klevu-1234567890&klevu_term=red%20shoes&klevu_totalResults=35&klevu_typeOfQuery=WILDCARD_AND\", requestOptions)\n  .then(response => response.text())\n  .then(result => console.log(result))\n  .catch(error => console.log('error', error));",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "6DGdWEWXLComG0sNANahm",
        "code": "import requests\n\nurl = \"https://stats.ksearchnet.com/analytics/n-search/search?apiKey=klevu-1234567890&term=red%20shoes&klevu_totalResults=35&klevu_typeOfQuery=WILDCARD_AND\"\n\npayload={}\nheaders = {}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\nprint(response.text)\n",
        "language": "python",
        "customLabel": ""
      },
      {
        "id": "ZX8_wo0Tig8YCFpmpqeIo",
        "code": "require \"uri\"\nrequire \"net/http\"\n\nurl = URI(\"https://stats.ksearchnet.com/analytics/n-search/search?apiKey=klevu-1234567890&term=red%20shoes&klevu_totalResults=35&klevu_typeOfQuery=WILDCARD_AND\")\n\nhttps = Net::HTTP.new(url.host, url.port)\nhttps.use_ssl = true\n\nrequest = Net::HTTP::Get.new(url)\n\nresponse = https.request(request)\nputs response.read_body\n",
        "language": "ruby",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "8jgVxehuUIB8HJb3WWGYb"
  },
  "description": "Use this API endpoint to submit the search activities:\n1.  When the search response is received\n2. And also when a facet is clicked (triggering a follow up query)\n\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-product-searches",
  "legacyHash": "Ipf54-3vQYQlnxuq6ZTx6"
}
```
:::



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/productTracking",
  "name": "Reporting Product Clicks From Search Results",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "klevu_apiKey",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "klevu_keywords",
        "type": "string",
        "description": "This is the term being searched. For example: iphone 5s.\n\n*For tracking of a facet click, append the selected facet to the term.\ne.g  iphone 5s [[color:black]]"
      },
      {
        "kind": "required",
        "name": "klevu_type",
        "type": "string",
        "description": "This is constant value. The value must be clicked."
      },
      {
        "kind": "required",
        "name": "klevu_productId",
        "type": "string",
        "description": "This is the Klevu ID of the clicked product. eg. 54321-12345."
      },
      {
        "kind": "required",
        "name": "klevu_productGroupId",
        "type": "string",
        "description": "This is the parent ID of the clicked product. eg. 54321. For compound products with a parent and multiple child/variant products, this is the common ID which ties the products together. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "required",
        "name": "klevu_productVariantId",
        "type": "string",
        "description": "This is the child/variant ID of the clicked product. eg. 12345. For compound products with a parent and multiple child/variant products, this is the ID of the specific variant. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "required",
        "name": "klevu_productName",
        "type": "string",
        "description": "This is the product name of the clicked product."
      },
      {
        "kind": "required",
        "name": "klevu_productUrl",
        "type": "string",
        "description": "This is the product URL of the clicked product."
      },
      {
        "kind": "required",
        "name": "klevu_shopperIP",
        "type": "string",
        "description": "IP address of the shopper who clicked on a product. \n\n*If calling from javascript (i.e. an ajax call), this is an optional parameter."
      },
      {
        "name": "klevu_shopperIP_v4",
        "kind": "optional",
        "type": "string",
        "description": "IPv4 address of the shopper who clicked a product.\n",
        "children": []
      },
      {
        "name": "klevu_shopperIP_v6",
        "kind": "optional",
        "type": "string",
        "description": "IPv6 address of the shopper who clicked a product.",
        "children": []
      },
      {
        "name": "data_protection",
        "kind": "optional",
        "type": "Boolean",
        "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true.",
        "children": []
      },
      {
        "name": "klevu_uuid",
        "kind": "optional",
        "type": "string",
        "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid",
        "children": []
      },
      {
        "name": "klevu_country",
        "kind": "optional",
        "type": "string",
        "description": "2-digit country code of the shopper who searched a term. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes",
        "children": []
      },
      {
        "name": "klevu_city",
        "kind": "optional",
        "type": "string",
        "description": "City name of the shopper who clicked a product.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "ewnRZCOKsK8s4PdjFvhyM",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_keywords=red%2520shoes&klevu_type=clicked&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%2520Trainers&klevu_productUrl=https%253A%252F%252Fyour.website.com%252Fproduct-url',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      },
      {
        "id": "EQqDeUhwCKDCWovOoWPGC",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_keywords=red%20shoes&klevu_type=clicked&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%20Trainers&klevu_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "8jgVxehuUIB8HJb3WWGYb",
        "code": "var xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"GET\", \"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_keywords=red%2520shoes&klevu_type=clicked&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%2520Trainers&klevu_productUrl=https%253A%252F%252Fyour.website.com%252Fproduct-url\");\n\nxhr.send();",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "6DGdWEWXLComG0sNANahm",
        "code": "import requests\n\nurl = \"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_keywords=red%20shoes&klevu_type=clicked&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%20Trainers&klevu_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url\"\n\npayload={}\nheaders = {}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\nprint(response.text)\n",
        "language": "python",
        "customLabel": ""
      },
      {
        "id": "ZX8_wo0Tig8YCFpmpqeIo",
        "code": "require \"uri\"\nrequire \"net/http\"\n\nurl = URI(\"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_keywords=red%20shoes&klevu_type=clicked&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%20Trainers&klevu_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url\")\n\nhttps = Net::HTTP.new(url.host, url.port)\nhttps.use_ssl = true\n\nrequest = Net::HTTP::Get.new(url)\n\nresponse = https.request(request)\nputs response.read_body\n",
        "language": "ruby",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "8jgVxehuUIB8HJb3WWGYb"
  },
  "description": "Use this API endpoint to submit the product clicks from search results.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-product-clicks-from-search-results",
  "legacyHash": "-2qMTxhJIQMvtMeZ8hbid"
}
```
:::


[title] No Results Customisations
[path] Guide/Dashboard Settings/

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://js.klevu.com/klevu-js-v1/klevu-js-api/{{JS_API_KEY}}.json",
  "name": "No results customisations",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "JS_API_KEY",
        "type": "string",
        "description": "Your public Klevu JS API Key.\n"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "Y1Vx38kZQPtiLmsufAFM_",
        "code": "{\n    \"klevu_showBannerAds\": true,\n    \"klevu_multiSelectFilters\": true,\n    \"klevu_abTestActive\": false,\n    \"klevu_userAnalyticsDomain\": \"stats.klevu.com\",\n    \"klevu_uc_userOptions\": {\n        \"showRolloverImage\": false,\n        \"showProductSwatches\": false,\n        \"enablePersonalisationInCatNav\": false,\n        \"showRatingsCountOnCategoryPage\": false,\n        \"outOfStockCaption\": \"Sold-Out\",\n        \"noResultsOptions\": {\n            \"showPopularProducts\": true,\n            \"productsHeading\": \"You may like...\",\n            \"showPopularKeywords\": true,\n            \"messages\": [\n                {\n                    \"showForTerms\": [\n                        \"jsbueruru\"\n                    ],\n                    \"message\": \"<a href=&#x22;http:&#47;&#47;klevu.com&#x22;>Klevu<&#47;a>\"\n                },\n                {\n                    \"showForTerms\": null,\n                    \"message\": \"Oh no! We can&#39;t find <B>#<&#47;B> </br>Please visit our website <a href=&#x22;https:&#47;&#47;klevu.com&#x22;> Klevu.com <&#47;a>\"\n                }\n            ],\n            \"banners\": [\n                {\n                    \"showForTerms\": [\n                        \"teeees\"\n                    ],\n                    \"showOnLandingPage\": true,\n                    \"redirectUrl\": \"https://demo.ksearchmisc.com/klevusearch/men/shirts/plaid-cotton-shirt-452.html\",\n                    \"showOnQuickSearch\": true,\n                    \"bannerImageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/wysiwyg/homepage-three-column-promo-03.png\",\n                    \"bannerRef\": 1187\n                },\n                {\n                    \"showForTerms\": null,\n                    \"showOnLandingPage\": true,\n                    \"redirectUrl\": \"https://demo.ksearchmisc.com/klevusearch/men/shirts.html\",\n                    \"showOnQuickSearch\": true,\n                    \"bannerImageUrl\": \"https://demo.ksearchmisc.com/klevusearch/skin/frontend/base/default/images/klevubanner/klevu-banner-ad-shirt-new.jpg\",\n                    \"bannerRef\": 993\n                }\n            ]\n        },\n        \"noImageUrl\": \"/klevu-js-v1/img-1-1/place-holder.jpg\",\n        \"showRatingsOnCategoryPage\": true,\n        \"showTrendingProductsCaption\": \"Trending Products\",\n        \"enablePersonalisationInSearch\": false,\n        \"isFullImageUrlProvided\": false,\n        \"showSearchBoxOnLandingPage\": false,\n        \"showRecentlyViewedItemsCaption\": \"Recently Viewed\",\n        \"priceInterval\": \"500\",\n        \"priceFormatter\": {\n            \"thousandSeparator\": \",\",\n            \"decimalPlaces\": \"0\",\n            \"decimalSeparator\": \".\",\n            \"appendCurrencyAtLast\": false,\n            \"currencySymbol\": \"$\"\n        },\n        \"showRatingsCountOnSearchResultsLandingPage\": false,\n        \"showRecentlyViewedItems\": true,\n        \"showTrendingProducts\": true,\n        \"showRatingsOnQuickSearches\": true,\n        \"showRatingsCountOnQuickSearches\": false,\n        \"showRatingsOnSearchResultsLandingPage\": true,\n        \"showFiltersInMobile\": false\n    },\n    \"klevu_cmsAnalyticsDomain\": \"stats.klevu.com\",\n    \"klevu_showOutOfStock\": true,\n    \"klevu_logoFreeSearch\": true,\n    \"klevu_layoutView\": \"grid\",\n    \"klevu_showPopuralTerms\": false,\n    \"klevu_showProductCode\": true,\n    \"klevu_showPopularSearches\": true,\n    \"klevu_cmsApiKey\": \"klevu-14551849541532921\",\n    \"klevu_categorySearchEnabled\": true,\n    \"klevu_showPriceSlider\": true,\n    \"klevu_addToCartEnabled\": false,\n    \"klevu_productsToShowInSlimLayout\": \"4\",\n    \"klevu_cmsEnabled\": true,\n    \"klevu_filtersOnLeft\": true,\n    \"klevu_showPrices\": true,\n    \"klevu_isSearchActive\": true,\n    \"klevu_filtersEnabled\": true,\n    \"klevu_fluidLayoutEnabled\": true,\n    \"klevu_webstorePopularTerms\": [\n        \"jeans\",\n        \"denims\",\n        \"dresss\",\n        \"dresses\",\n        \"pall\"\n    ],\n    \"klevu_cmsSearchDomain\": \"eucs2.klevu.com\",\n    \"klevu_lookForDataInSameFeed\": true,\n    \"klevu_popularProductsOfSite\": [\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/w/s/wsd013t_1.jpg\",\n            \"name\": \"Lafayette Convertible Dress\",\n            \"id\": \"425-310\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/lafayette-convertible-dress.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/a/b/abl005a_1.jpg\",\n            \"name\": \"Roller Suitcase\",\n            \"id\": \"375\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/roller-suitcase.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/w/s/wsd008t_1.jpg\",\n            \"name\": \"Ludlow Sheath Dress\",\n            \"id\": \"424-309\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/ludlow-sheath-dress.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/4/1/41cwpqsxuil.jpg\",\n            \"name\": \"Apple iPad Mini 2 Tablet (7.9 inch, 32 GB, Wi-Fi Only), Silver\",\n            \"id\": \"898\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/apple-ipad-mini-2-tablet-7-9-inch-32-gb-wi-fi-only-silver.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/a/b/abl0006a_4.jpg\",\n            \"name\": \"Classic Hardshell Suitcase\",\n            \"id\": \"436-541\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/classic-hardshell-suitcase-591.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/p/m/pmo000a_5.jpg\",\n            \"name\": \"Thomas Overcoat\",\n            \"id\": \"808-570\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/thomas-overcoat.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/a/b/abl003b_1.jpg\",\n            \"name\": \"Broad St. Flapover Briefcase\",\n            \"id\": \"373\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/flapover-briefcase.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/p/w/pwt001a_1.jpg\",\n            \"name\": \"Gans Trench Coat\",\n            \"id\": \"832-713\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/gans-trench-coat.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/s/h/shm003a_5.jpg\",\n            \"name\": \"Lenox Boot\",\n            \"id\": \"867-767\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/lenox-boot.html\"\n        },\n        {\n            \"imageUrl\": \"https://demo.ksearchmisc.com/klevusearch/media/klevu_images/m/s/msj009t_3.jpg\",\n            \"name\": \"Sullivan Sport Coat\",\n            \"id\": \"405-242\",\n            \"url\": \"https://demo.ksearchmisc.com/klevusearch/oxford-sport-coat-456.html\"\n        }\n    ],\n    \"klevuLayoutVersion\": \"-1-1\",\n    \"klevu_loadMapFile\": true,\n    \"klevu_layoutType\": \"slim\",\n    \"klevu_apiDomain\": \"api.ksearchnet.com\",\n    \"klevu_userSearchDomain\": \"eucs2.klevu.com\",\n    \"klevu_showRecentSerches\": true,\n    \"klevu_userJavascriptDomain\": \"js.klevu.com\"\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Y1Vx38kZQPtiLmsufAFM_"
  },
  "examples": {
    "languages": [
      {
        "id": "3AdeysJML2Tq9WYHSdiJU",
        "code": "curl --location --request GET 'https://js.klevu.com/klevu-js-v1/klevu-js-api/klevu-14551849541532921.json'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3AdeysJML2Tq9WYHSdiJU"
  },
  "description": "This API call will retrieve the Klevu site-specific data which also include the popular products. The popular products can be found in the field klevu_popularProductsOfSite.\n",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "no-results-customisations",
  "legacyHash": "uFN0pI-f3BZCXFZPdr81Q"
}
```
:::


[title] Customers Also Bought
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any products which other customers also purchased, in addition to the current product. The most common placements for this banner type are:

**Cart: Customers Also Bought**
Show a recommendation banner with products other customers also purchased from the store.

**Product Page: Customers Also Bought**
Show a recommendation banner with products other customer bought together with the product currently being viewed.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Customers Also Bought Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify RECS_ALSO_BOUGHT."
      },
      {
        "kind": "required",
        "name": "recentObjects",
        "type": "String",
        "description": "The Klevu ID of the product or products you will use for context. Klevu will find other products which were viewed in addition to the ones specified in this field."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 13,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsAlsoBought\",\n            \"meta\": {\n                \"qTime\": 8,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 8,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"color\": \"black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192758132867\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904862257283\",\n                    \"price\": \"15.64\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649406_medium.jpg?v=1611184245&vid=34322635718787,34322635882627,34322636112003,34322636275843\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322636275843\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649407_medium.jpg?v=1611184245&vid=34322636472451,34322636603523,34322636734595,34322636898435\",\n                    \"sku\": \"21417591-black-xxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"14.54\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649406_medium.jpg?v=1611184245&vid=34322635718787,34322635882627,34322636112003,34322636275843\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"15.64\",\n                    \"swatchesInfo\": \"variantColor1:white ;;;; variantColor3:light gray ;;;; variantColor2:black ;;;; variantColor5:Coffee ;;;; variantColor4:wine red ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649407_medium.jpg?v=1611184245&vid=16847190786179 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649406_medium.jpg?v=1611184245&vid=16847200452739 ;;;; variantId4:34322636996739 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649409_medium.jpg?v=1611184382&vid=16847236366467 ;;;; variantId5:34322637389955 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649408_medium.jpg?v=1611184245&vid=16847192424579 ;;;; variantId2:34322635718787 ;;;; variantId3:34322636472451 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1315649405_medium.jpg?v=1611184330&vid=16847231287427 ;;;; variantId1:34322634965123 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/new-autumn-mens-pullover-casual-knitted-sweaters-male-turtleneck-mans-black-solid-knitwear-slim-brand-clothing-sweater\",\n                    \"size\": \"XXL\",\n                    \"name\": \"Men's Pullover Casual Knitted Sweaters\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Faddare Origin: CN(Origin) Pattern Type: Solid Collar: Tur\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757346435\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904837419139\",\n                    \"price\": \"36.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672939_medium.jpg?v=1611184379&vid=34322615861379,34322616189059,34322616647811,34322617139331,34322617565315,34322617925763\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322617925763\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672940_medium.jpg?v=1611184282&vid=34322609275011,34322609766531,34322610192515,34322610552963,34322618318979,34322618679427\",\n                    \"sku\": \"30479271-black-xxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672939_medium.jpg?v=1611184379&vid=34322615861379,34322616189059,34322616647811,34322617139331,34322617565315,34322617925763\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"36.0\",\n                    \"swatchesInfo\": \"variantColor1:Gray ;;;; variantColor3:Ivory ;;;; variantColor2:Dark Grey ;;;; variantColor5:Gray ;;;; variantColor4:Black ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/ivory.png?v=1587554095 ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672942_medium.jpg?v=1611184362&vid=16847232794755 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672941_medium.jpg?v=1611184324&vid=16847230926979 ;;;; variantId4:34322615861379 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672940_medium.jpg?v=1611184282&vid=16847228698755 ;;;; variantId5:34322618318979 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672939_medium.jpg?v=1611184379&vid=16847235842179 ;;;; variantId2:34322611044483 ;;;; variantId3:34322613436547 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1153672940_medium.jpg?v=1611184282&vid=16847228698755 ;;;; variantId1:34322609275011 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 1,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/zogaa-men-sweaters-2019-brand-new-warm-pullover-sweaters-man-casual-knitwear-winter-men-black-sweatwer-xxxl-computer-knitted\",\n                    \"size\": \"XXL\",\n                    \"name\": \"Men Sweaters Brand New Warm Pullover Sweaters Man Casual Knitwear Men Sweater Computer Knitted\",\n                    \"shortDesc\": \"closure:closure:none; decoration:decoration:none; ;;;; Gender: MEN Style: Casual Material: Cotton Material: Polyeste\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753971331\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"19.38\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372030_medium.jpg?v=1611183857&vid=34322486722691,34322486820995,34322486952067,34322487246979,34322487509123\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322486952067\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372030_medium.jpg?v=1611183857&vid=34322486722691,34322486820995,34322486952067,34322487246979,34322487509123\",\n                    \"sku\": \"26134087-black-xl\",\n                    \"closure\": \"Single Breasted\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"17.38\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372030_medium.jpg?v=1611183857&vid=34322486722691,34322486820995,34322486952067,34322487246979,34322487509123\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"19.38\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor3:White ;;;; variantColor2:Red ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372032_medium.jpg?v=1611184290&vid=16847229059203 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372031_medium.jpg?v=1611183968&vid=16847195799683 ;;;; variantId2:34322487738499 ;;;; variantId3:34322489639043 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-967372030_medium.jpg?v=1611183857&vid=16847173943427 ;;;; variantId1:34322486722691 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Shirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2019-new-mens-chinese-vintage-shirt-mandarin-collar-slim-fit-short-sleeves-cotton-linen-shirt-white-red-black-casual-shirt-tops\",\n                    \"fabric\": \"Broadcloth\",\n                    \"name\": \"New Men's Chinese Vintage Shirt Mandarin Collar Slim Fit Short Sleeves Cotton Linen Shirt Casual Shirt Tops\",\n                    \"shortDesc\": \"fabric:fabric:broadcloth; closure:closure:single breasted; ;;;; Gender: MEN Item Type: Shirts Shirts Type: Casual Shirts Mate\",\n                    \"category\": \"All;;Mens Shirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759214211\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"40.10\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627119_medium.jpg?v=1611183943&vid=34322649088131,34322650267779,34322651906179,34322653216899,34322654363779,34322655576195\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322655576195\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627119_medium.jpg?v=1611183943&vid=34322649088131,34322650267779,34322651906179,34322653216899,34322654363779,34322655576195\",\n                    \"sku\": \"25093720-black-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"closure\": \"Single Breasted\",\n                    \"decoration\": \"Pockets\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627119_medium.jpg?v=1611183943&vid=34322649088131,34322650267779,34322651906179,34322653216899,34322654363779,34322655576195\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"40.1\",\n                    \"swatchesInfo\": \"variantColor1:black ;;;; variantColor3:darkblue ;;;; variantColor2:brown ;;;; variantColor5:gray ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor4:darkgray ;;;; variantColor6:red ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627124_medium.jpg?v=1611183993&vid=16847200845955 ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627120_medium.jpg?v=1611184005&vid=16847203238019 ;;;; variantId6:34322680545411 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627121_medium.jpg?v=1611183969&vid=16847195996291 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627122_medium.jpg?v=1611184385&vid=16847237873795 ;;;; variantId4:34322669961347 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627123_medium.jpg?v=1611183943&vid=16847186886787 ;;;; variantId5:34322675400835 ;;;; variantId2:34322656526467 ;;;; variantId3:34322663571587 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-938627119_medium.jpg?v=1611183943&vid=16847185707139 ;;;; variantId1:34322649088131 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2019-autumn-and-winter-models-high-collar-cardigan-sweater-men-new-mens-plus-velvet-thick-white-sweater-coat-personality-retro\",\n                    \"name\": \"High Collar Cardigan Sweater Men\",\n                    \"shortDesc\": \"closure:closure:single breasted; decoration:decoration:pockets; ;;;; Gender: MEN Technics: Computer Knitted Thickness: STANDARD\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men\",\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756035715\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"29.48\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145441_medium.jpg?v=1611184270&vid=34322535186563,34322536038531,34322536956035,34322537971843,34322538856579\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322535186563\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145443_medium.jpg?v=1611183900&vid=34322524864643,34322525782147,34322526994563,34322528141443,34322529288323\",\n                    \"sku\": \"31718415-black-us-size-xxl\",\n                    \"closure\": \"Single Breasted\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"24.06\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145441_medium.jpg?v=1611184270&vid=34322535186563,34322536038531,34322536956035,34322537971843,34322538856579\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"29.48\",\n                    \"swatchesInfo\": \"variantColor1:White ;;;; variantColor3:Red ;;;; variantColor2:Sliver ;;;; variantColor5:Royal Blue ;;;; variantColor4:Gold ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantColor6:Black ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145441_medium.jpg?v=1611184270&vid=16847227879555 ;;;; variantId6:34322535186563 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145444_medium.jpg?v=1611184262&vid=16847226503299 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145445_medium.jpg?v=1611184259&vid=16847225946243 ;;;; variantId4:34322524864643 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145442_medium.jpg?v=1611184319&vid=16847230730371 ;;;; variantId5:34322530566275 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145443_medium.jpg?v=1611183900&vid=16847175417987 ;;;; variantId2:34322515067011 ;;;; variantId3:34322519720067 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1325145446_medium.jpg?v=1611183977&vid=16847197798531 ;;;; variantId1:34322508251267 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Shirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/royal-blue-silk-satin-shirt-men-2019-luxury-brand-new-slim-fit-mens-dress-shirts-wedding-party-casual-male-casual-shirt-chemise\",\n                    \"fabric\": \"Broadcloth\",\n                    \"name\": \"Royal Silk Satin Shirt Men New Slim Fit Men's Dress Shirts Wedding Party Casual Male Casual Shirt Chemise\",\n                    \"shortDesc\": \"gender:gender:men; fabric:fabric:broadcloth; closure:closure:single breasted; ;;;; Brand Name: PARKLEES Origin: CN(Origin) Material: Rayon\",\n                    \"category\": \"All;;Mens Shirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757018755\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904831127683\",\n                    \"price\": \"32.84\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664999_medium.jpg?v=1611184219&vid=34322605768835,34322606850179,34322607210627,34322607636611,34322608095363\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322606850179\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664999_medium.jpg?v=1611184219&vid=34322605768835,34322606850179,34322607210627,34322607636611,34322608095363\",\n                    \"sku\": \"36576693-black-xxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"27.92\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664999_medium.jpg?v=1611184219&vid=34322605768835,34322606850179,34322607210627,34322607636611,34322608095363\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.84\",\n                    \"swatchesInfo\": \"variantColor1:Gray ;;;; variantColor3:Gray ;;;; variantColor2:Navy Blue ;;;; variantColor5:Gray ;;;; variantColor4:Black ;;;; variantColor6:Black ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664999_medium.jpg?v=1611184219&vid=16847189606531 ;;;; variantId6:34322606850179 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664998_medium.jpg?v=1611184300&vid=16847229583491 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391665000_medium.jpg?v=1611184219&vid=16847199076483 ;;;; variantId4:34322605768835 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664998_medium.jpg?v=1611184300&vid=16847229583491 ;;;; variantId5:34322606030979 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664999_medium.jpg?v=1611184219&vid=16847189606531 ;;;; variantId2:34322603999363 ;;;; variantId3:34322605375619 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1391664998_medium.jpg?v=1611184300&vid=16847229583491 ;;;; variantId1:34322603671683 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2019-autumn-mens-sweater-pullovers-simple-style-knitted-v-neck-sweater-jumpers-thin-male-knitwear-blue-black-m-3xl-men-clothes\",\n                    \"size\": \"XXL\",\n                    \"name\": \"Men's Sweater Pullovers Simple Style Knitted V Neck Sweater Jumpers Thin Male Knitwear M- Men Clothes\",\n                    \"shortDesc\": \"gender:gender:men,youth;men]]>; season:season:spring;autumn;winter; decoration:decoration:none; closure:closure:zipper; ;;;; Brand Name: UNIVOS KUNI Model Number: J761\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192758231171\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904867401859\",\n                    \"price\": \"38.28\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920545_medium.jpg?v=1611183989&vid=34322640666755,34322640699523,34322640732291,34322640765059,34322640797827\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322640666755\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920546_medium.jpg?v=1611183942&vid=34322640830595,34322640863363,34322640896131,34322640928899,34322640961667\",\n                    \"sku\": \"9352560-black-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"38.28\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920545_medium.jpg?v=1611183989&vid=34322640666755,34322640699523,34322640732291,34322640765059,34322640797827\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"38.28\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor3:Red ;;;; variantColor2:Dark blue ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920547_medium.jpg?v=1611183997&vid=16847201796227 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920546_medium.jpg?v=1611183942&vid=16847190360195 ;;;; variantId2:34322640830595 ;;;; variantId3:34322640994435 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-939920545_medium.jpg?v=1611183989&vid=16847199993987 ;;;; variantId1:34322640666755 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 1,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/woodvoice-brand-mens-fashion-sweater-solid-color-male-high-quality-brand-street-wear-pullover-sweaters-blue-black-red-hot-sale\",\n                    \"size\": \"M\",\n                    \"name\": \"Woodvoice Men's Fashion Sweater\",\n                    \"shortDesc\": \"size:size:M,L,XL,XXL,XXXL; closure:closure:none; decoration:decoration:none; ;;;; Gender: MEN Style: Casual Material: Acrylic\",\n                    \"category\": \"All;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men, Men\",\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754430083\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"16.12\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601388_medium.jpg?v=1611184228&vid=34322507530371,34322508185731,34322509201539,34322510151811,34322511167619,34322512183427,34322549244035\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"no\",\n                    \"id\": \"34322509201539\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601407_medium.jpg?v=1611184228\",\n                    \"sku\": \"17014311-black-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"closure\": \"[Single Breasted, Single Button]\",\n                    \"startPrice\": \"14.44\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601388_medium.jpg?v=1611184228&vid=34322507530371,34322508185731,34322509201539,34322510151811,34322511167619,34322512183427,34322549244035\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"16.12\",\n                    \"swatchesInfo\": \"variantColor1:Wine ;;;; variantColor3:Black ;;;; variantColor2:Green ;;;; variantColor5:J264Green ;;;; variantColor4:Navy ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor6:Purple ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601399_medium.jpg?v=1611184294&vid=16847229288579 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601388_medium.jpg?v=1611184228&vid=16847185674371 ;;;; variantId6:34322524569731 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601394_medium.jpg?v=1611184228&vid=16847196192899 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601403_medium.jpg?v=1611184228&vid=16847191769219 ;;;; variantId4:34322513330307 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601408_medium.jpg?v=1611184228&vid=16847191474307 ;;;; variantId5:34322518999171 ;;;; variantId2:34322501435523 ;;;; variantId3:34322507530371 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1411601401_medium.jpg?v=1611184267&vid=16847227355267 ;;;; variantId1:34322492293251 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Shirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 0,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/jeetoo-white-men-shirt-2019-new-business-mens-regular-fit-dress-shirt-male-solid-long-sleeves-casua-wedding-shirt-plus-size-3xl\",\n                    \"fabric\": \"[Broadcloth, Broadcloth]\",\n                    \"name\": \"Jeetoo Men Shirt New Business Men's Regular Fit Dress Shirt Male Solid Long Sleeves Casual Wedding Shirt\",\n                    \"shortDesc\": \"gender:gender:men,men; fabric:fabric:broadcloth,broadcloth; closure:closure:single breasted,single button; ;;;; Brand Name: JeeToo Origin: CN(Origin) Material\",\n                    \"category\": \"All;;Mens Shirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsAlsoBought\",\n      \"typeOfRequest\": \"RECS_ALSO_BOUGHT\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322443665539\n                },\n                {\n                  \"id\": 34322633916547\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsAlsoBought\",\n      \"typeOfRequest\": \"RECS_ALSO_BOUGHT\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322443665539\n                },\n                {\n                  \"id\": 34322633916547\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"recsAlsoBought\",\"typeOfRequest\":\"RECS_ALSO_BOUGHT\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322443665539},{\"id\":34322633916547}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"recsAlsoBought\\\",\\n      \\\"typeOfRequest\\\": \\\"RECS_ALSO_BOUGHT\\\",\\n      \\\"settings\\\": {\\n        \\\"context\\\": {\\n          \\\"recentObjects\\\": [\\n            {\\n              \\\"typeOfRecord\\\": \\\"KLEVU_PRODUCT\\\",\\n              \\\"records\\\": [\\n                {\\n                  \\\"id\\\": 34322443665539\\n                },\\n                {\\n                  \\\"id\\\": 34322633916547\\n                }\\n              ]\\n            }\\n          ]\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-158755634955912036\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"recsAlsoBought\",\"typeOfRequest\":\"RECS_ALSO_BOUGHT\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322443665539},{\"id\":34322633916547}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "The end-point is used for retrieving customers also bought product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "customers-also-bought-product-recommendations",
  "legacyHash": "rqHd-ym9AuoHXtvTXwYCJ"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=alsoBought&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] New Arrivals
[path] Guide/Smart Recommendations/

:::hint{type="info"}
f you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing the newest products in the store. The most common placements for this banner type are:

**Homepage: New Arrivals**
Show a recommendation banner with the newest products across the entire store.

**Category Page: New Arrivals in \{Category}**
Show a banner with the newest products within a specific category.

The *newness* of each product is determined by an attribute in your catalogue which can be configured via our Klevu Support team. It could be the Product ID or a date field, for example.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "New Arrivals Product Recommendations",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify RECS_NEW_ARRIVALS."
      },
      {
        "kind": "optional",
        "name": "categoryPath",
        "type": "string",
        "description": "This is only required when you want to give Category-specific context to a recommendation query. Specify the name of the category to retrieve results from, in the same case and format as it is indexed with Klevu.\n\nFor nested categories, use the ; character to separate the hierarchy. For example, for 'Mens > Shoes > Trainers and Sneakers' you would specify: Mens;Shoes;Trainers and Sneakers."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 17,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsNewArrivals\",\n            \"meta\": {\n                \"qTime\": 15,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 26,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": false\n            },\n            \"records\": [\n                {\n                    \"color\": \"3D 3\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192760524931\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"28.54\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178419_medium.jpg?v=1611183938&vid=34322715246723,34322715279491,34322715312259,34322715345027,34322715377795,34322715410563,34322715443331,34322715476099,34322715508867,34322715541635,34322715574403,34322715607171\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322715607171\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178417_medium.jpg?v=1611183938&vid=34322713673859,34322713739395,34322713804931,34322713870467,34322713936003,34322714001539,34322714067075,34322714132611,34322714198147,34322714263683,34322714329219,34322714394755,34322715115651,34322715148419,34322715181187\",\n                    \"sku\": \"31527085-3d-3-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.82\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178419_medium.jpg?v=1611183938&vid=34322715246723,34322715279491,34322715312259,34322715345027,34322715377795,34322715410563,34322715443331,34322715476099,34322715508867,34322715541635,34322715574403,34322715607171\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"28.54\",\n                    \"swatchesInfo\": \"variantColor1:3D 5 ;;;; variantColor3:3D 5 ;;;; variantColor2:3D 6 ;;;; variantColor5:3D 7 ;;;; variantColor4:3D 6 ;;;; variantColor6:3D 6 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178422_medium.jpg?v=1611184010&vid=16847203926147 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178421_medium.jpg?v=1611184011&vid=16847204155523 ;;;; variantId6:34322709741699 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178422_medium.jpg?v=1611184010&vid=16847203926147 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178423_medium.jpg?v=1611183938&vid=16847188230275 ;;;; variantId4:34322709250179 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178422_medium.jpg?v=1611184010&vid=16847203926147 ;;;; variantId5:34322709512323 ;;;; variantId2:34322707513475 ;;;; variantId3:34322707644547 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1316178421_medium.jpg?v=1611184011&vid=16847204155523 ;;;; variantId1:34322707153027 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Coats & Jackets;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/neon-green-hoody-men-women-harajuku-clothes-store-for-customization-3d-hoodie-sweatshirt-street-colorful-print-hip-hop-trend-4xl\",\n                    \"size\": \"XL\",\n                    \"name\": \"3D Hoodie Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:men,women; size:size:,OVERSIZED; season:season:autumn,winter,spring; closure:closure:none; ;;;; Brand Name: aikooki Sleeve Length(cm): Full Clot\",\n                    \"category\": \"All;;Women Coats & Jackets;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759836803\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234340_medium.jpg?v=1611184264\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322682871939\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882497-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234340_medium.jpg?v=1611184264\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 2,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-navy-blue-zipper-hooded-fleece-sweatshirt-ox00006\",\n                    \"name\": \"WoMen's Zipper Hooded Fleece Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: Happiness ist. Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Dk Blue\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759410819\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"300.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-966181077_medium.jpg?v=1611183929&vid=34322645876867,34322646433923,34322646958211\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322646958211\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-966181077_medium.jpg?v=1611183929&vid=34322645876867,34322646433923,34322646958211\",\n                    \"sku\": \"26101891-dk-blue-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-966181077_medium.jpg?v=1611183929&vid=34322645876867,34322646433923,34322646958211\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"300.0\",\n                    \"swatchesInfo\": \"variantColor1:dk blue ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-966181077_medium.jpg?v=1611183929&vid=16847187607683 ;;;; variantId1:34322645876867 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Coats & Jackets;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 2,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/high-grade-100-cotton-knit-womens-new-fashion-hooded-zipper-sweatshirts-warm-thick-dark-blue-s-m-l\",\n                    \"fabric\": \"Knitted\",\n                    \"name\": \"100% Cotton Knit Women's New Fashion Hooded Zipper Sweatshirts\",\n                    \"shortDesc\": \"fabric:fabric:knitted; ;;;; Gender: WOMEN Item Type: Hoodies Item Type: Sweatshirts Sleeve Length(cm): Full\",\n                    \"category\": \"All;;Women Coats & Jackets;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black 2\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192758067331\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"28.48\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152411_medium.jpg?v=1611184378&vid=34322640142467,34322640175235,34322640470147,34322640502915,34322640535683,34322640568451\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322640568451\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152414_medium.jpg?v=1611184222\",\n                    \"sku\": \"39828275-black-2-xxxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.98\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152411_medium.jpg?v=1611184378&vid=34322640142467,34322640175235,34322640470147,34322640502915,34322640535683,34322640568451\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"28.48\",\n                    \"swatchesInfo\": \"variantColor1:Black 13 ;;;; variantColor3:Black 13 ;;;; variantColor2:Gary ;;;; variantColor5:Gary ;;;; variantColor4:Red ;;;; variantColor6:Red ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152402_medium.jpg?v=1611184222&vid=16847187804291 ;;;; variantSwatchImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152422_medium.jpg?v=1611184222&vid=16847197700227 ;;;; variantId6:34322637193347 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152403_medium.jpg?v=1611184222&vid=16847191638147 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152403_medium.jpg?v=1611184222&vid=16847191638147 ;;;; variantId4:34322636505219 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152402_medium.jpg?v=1611184222&vid=16847187804291 ;;;; variantId5:34322636963971 ;;;; variantId2:34322635456643 ;;;; variantId3:34322636046467 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1624152422_medium.jpg?v=1611184222&vid=16847197700227 ;;;; variantId1:34322635227267 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/kawaii-hunter-x-hunter-hoodies-men-women-short-sleeve-sweatshirt-killua-zoldyck-anime-manga-black-hoodies-bluzy-tops-clothes\",\n                    \"size\": \"XXXL\",\n                    \"name\": \"Short Sleeve Sweatshirt\",\n                    \"shortDesc\": \"closure:closure:none; ;;;; Brand Name: Dshztooma Origin: CN(Origin) Sleeve Length(cm): Full Style: Casual\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756265091\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"389.64\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232586_medium.jpg?v=1611184219&vid=34322564546691,34322567102595,34322567757955,34322568282243,34322568773763\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322568773763\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232586_medium.jpg?v=1611184219&vid=34322564546691,34322567102595,34322567757955,34322568282243,34322568773763\",\n                    \"sku\": \"42882449-black-xl-china\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232586_medium.jpg?v=1611184219&vid=34322564546691,34322567102595,34322567757955,34322568282243,34322568773763\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"389.64\",\n                    \"swatchesInfo\": \"variantColor1:White ;;;; variantColor3:White ;;;; variantColor2:Black ;;;; variantColor4:Black ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232587_medium.jpg?v=1611184219&vid=16847189377155 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232586_medium.jpg?v=1611184219&vid=16847189246083 ;;;; variantId4:34322567102595 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232586_medium.jpg?v=1611184219&vid=16847189246083 ;;;; variantId2:34322564546691 ;;;; variantId3:34322565169283 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232587_medium.jpg?v=1611184219&vid=16847189377155 ;;;; variantId1:34322563268739 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 9,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/havva-spring-autumn-new-fashion-round-neck-pullover-100-cotton-womens-pop-doodle-print-black-sweatshirt-v30640\",\n                    \"size\": \"XL\",\n                    \"name\": \"New Fashion Round-Neck Pullover 100% Cotton WoMen's Pop Doodle Print Sweatshirt\",\n                    \"ships_from\": \"China\",\n                    \"shortDesc\": \"gender:gender:women; fabric:fabric:cotton; age:age:ages 18-35 years old; ;;;; Brand Name: HAVVA Material: Cotton Item Type: Sweatshirts\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Green\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192755871875\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"234.12\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234141_medium.jpg?v=1611184211&vid=34322509136003,34322515787907,34322517688451\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322517688451\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234140_medium.jpg?v=1611184200&vid=34322507268227,34322511396995,34322513985667\",\n                    \"sku\": \"42882491-green-s\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234141_medium.jpg?v=1611184211&vid=34322509136003,34322515787907,34322517688451\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"234.12\",\n                    \"swatchesInfo\": \"variantColor1:Blue ;;;; variantColor3:Blue ;;;; variantColor2:Green ;;;; variantColor4:Green ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234140_medium.jpg?v=1611184200&vid=16847217393795 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234141_medium.jpg?v=1611184211&vid=16847218311299 ;;;; variantId4:34322515787907 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234141_medium.jpg?v=1611184211&vid=16847218311299 ;;;; variantId2:34322509136003 ;;;; variantId3:34322511396995 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234140_medium.jpg?v=1611184200&vid=16847217393795 ;;;; variantId1:34322507268227 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 5,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/spring-2020-new-autumn-women-casual-sporty-style-loose-knitted-cotton-sweatshirt-ladies-thick-blue-green-long-hoodies\",\n                    \"fabric\": \"Knitted\",\n                    \"name\": \"New Women Casual Sporty Style Loose Knitted Cotton Sweatshirt Ladies Thick / Long Hoodies\",\n                    \"shortDesc\": \"fabric:fabric:knitted; age:age:ages 18-35 years old; ;;;; Material: Spandex Material: Cotton Sleeve Style: Regular Sleeve Len\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"age\": \"Ages 18-35 Years Old\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"3D 5\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192755380355\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"26.96\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801482_medium.jpg?v=1611183908&vid=34322582929539,34322583257219,34322583584899,34322583912579,34322584273027,34322584666243,34322585026691,34322585452675\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322585452675\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801482_medium.jpg?v=1611183908&vid=34322582929539,34322583257219,34322583584899,34322583912579,34322584273027,34322584666243,34322585026691,34322585452675\",\n                    \"sku\": \"37091373-3d-5-xxxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"26.36\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801482_medium.jpg?v=1611183908&vid=34322582929539,34322583257219,34322583584899,34322583912579,34322584273027,34322584666243,34322585026691,34322585452675\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"26.96\",\n                    \"swatchesInfo\": \"variantColor1:3D ;;;; variantColor3:3D 12 ;;;; variantColor2:3D 11 ;;;; variantColor5:3D 6 ;;;; variantColor4:3D 7 ;;;; variantColor6:3D 7 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=16847231680643 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801489_medium.jpg?v=1611183980&vid=16847198191747 ;;;; variantId6:34322539380867 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801488_medium.jpg?v=1611184375&vid=16847234957443 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801483_medium.jpg?v=1611184373&vid=16847233941635 ;;;; variantId4:34322535940227 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801484_medium.jpg?v=1611184336&vid=16847231680643 ;;;; variantId5:34322537087107 ;;;; variantId2:34322517295235 ;;;; variantId3:34322525290627 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1548801478_medium.jpg?v=1611184383&vid=16847236628611 ;;;; variantId1:34322506481795 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/3d-printed-hoodies-one-piece-hoodie-men-sweatshirt-women-harajuku-pullovers-casual-hot-sale-anime-black-3d-hoodies-clothes\",\n                    \"size\": \"XXXL\",\n                    \"name\": \"3D Printed Hoodies One Piece Hoodie Men Sweatshirt Women Harajuku Pullovers Casual Hot Sale Anime 3D Hoodies Clothes\",\n                    \"shortDesc\": \"gender:gender:men,men; closure:closure:none; ;;;; Brand Name: Rholycrown Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754593923\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"32.08\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340729_medium.jpg?v=1611184264&vid=34322557829251,34322558648451,34322559238275,34322559959171,34322560712835,34322561532035\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322561532035\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340730_medium.jpg?v=1611183859&vid=34322527256707,34322528370819,34322529583235,34322530795651,34322534236291,34322535317635\",\n                    \"sku\": \"37965190-black-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"16.88\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340729_medium.jpg?v=1611184264&vid=34322557829251,34322558648451,34322559238275,34322559959171,34322560712835,34322561532035\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.08\",\n                    \"swatchesInfo\": \"variantColor1:Purple ;;;; variantColor3:Yellow ;;;; variantColor2:Red ;;;; variantColor5:Yellow ;;;; variantColor4:Red ;;;; variantColor6:Navy Blue ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantSwatchImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/red.png?v=1587554100 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340739_medium.jpg?v=1611183981&vid=16847198421123 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340738_medium.jpg?v=1611183981&vid=16847198486659 ;;;; variantId6:34322512281731 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340737_medium.jpg?v=1611183964&vid=16847195308163 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340738_medium.jpg?v=1611183981&vid=16847198486659 ;;;; variantId4:34322504679555 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340737_medium.jpg?v=1611183964&vid=16847195308163 ;;;; variantId5:34322507202691 ;;;; variantId2:34322497699971 ;;;; variantId3:34322502418563 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1447340736_medium.jpg?v=1611184271&vid=16847228141699 ;;;; variantId1:34322494455939 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 65,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2020-new-brand-paris-fashion-vetements-air-transport-dhl-hoodies-men-sweatshirts-men-and-women-sweatshirt-tops-letter-yellow-073\",\n                    \"size\": \"L\",\n                    \"name\": \"New Brand Paris Fashion Air Transport Dhl Hoodies Men Sweatshirts Men And Women Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: LIZHENDANZHE Sleeve Length(cm): Full Gender: MEN Style: Ca\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Women\",\n                    \"color\": \"White\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754331779\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"95.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322491310211\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"sku\": \"42882418-white-s\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=34322489016451,34322489901187,34322490818691,34322491310211\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"95.0\",\n                    \"swatchesInfo\": \"variantColor1:Black ;;;; variantColor3:Black ;;;; variantColor2:White ;;;; variantSwatchImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor5:Black ;;;; variantColor4:White ;;;; variantSwatchImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor6:White ;;;; variantSwatchImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId6:34322490818691 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId4:34322489901187 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantId5:34322490228867 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231578_medium.jpg?v=1611184237&vid=16847175745667 ;;;; variantId2:34322489016451 ;;;; variantId3:34322489409667 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231577_medium.jpg?v=1611184237&vid=16847218016387 ;;;; variantId1:34322488262787 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 7,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/private-butterfly-backpack-printed-casual-cut-white-unisex-sweatshirt-two-color-option\",\n                    \"name\": \"Private Butterfly Backpack Printed Casual Cut Unisex Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:women]]>; ;;;; Origin: TR(Origin) Item Type: Hoodies Material: Cotton Gender: WOMEN\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Blue-5\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753545347\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"32.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110681_medium.jpg?v=1611184237&vid=34322485903491,34322485936259,34322485969027\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322485969027\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110671_medium.jpg?v=1611184197&vid=34322484166787,34322484494467,34322484625539,34322484756611,34322484920451,34322485051523,34322485182595,34322485313667,34322485411971,34322485543043\",\n                    \"sku\": \"42346497-blue-5-6xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"25.6\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110681_medium.jpg?v=1611184237&vid=34322485903491,34322485936259,34322485969027\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"32.0\",\n                    \"swatchesInfo\": \"variantColor1:Red-5 ;;;; variantColor3:Red-5 ;;;; variantColor2:Red-4 ;;;; variantColor5:Red-2 ;;;; variantColor4:Red-3 ;;;; variantColor6:Red-4 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=16847224569987 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110679_medium.jpg?v=1611184197&vid=16847184625795 ;;;; variantId6:34322470862979 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110683_medium.jpg?v=1611184254&vid=16847224569987 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110678_medium.jpg?v=1611184234&vid=16847220736131 ;;;; variantId4:34322466865283 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110682_medium.jpg?v=1611184253&vid=16847224373379 ;;;; variantId5:34322470436995 ;;;; variantId2:34322460901507 ;;;; variantId3:34322463424643 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1646110679_medium.jpg?v=1611184197&vid=16847184625795 ;;;; variantId1:34322459394179 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/maidangdi-oversized-hoodie-loose-cotton-solid-color-sweatshirt-comfortable-leisure-furniture-outdoor-pullover-chinese-red-hoodie\",\n                    \"size\": \"6XL\",\n                    \"name\": \"Oversized Hoodie Loose Cotton Solid Sweatshirt Outdoor Pullover Chinese Hoodie\",\n                    \"shortDesc\": \"closure:closure:none; ;;;; Brand Name: MaiDangDi Origin: CN(Origin) Sleeve Length(cm): Full Style: Casual\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"orange2\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753610883\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"23.58\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462194_medium.jpg?v=1611184242&vid=34322484822147,34322484953219,34322485084291,34322485215363\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322485215363\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462192_medium.jpg?v=1611184202&vid=34322483380355,34322483478659,34322483609731,34322483740803,34322483871875,34322483970179\",\n                    \"sku\": \"42716014-orange2-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462194_medium.jpg?v=1611184242&vid=34322484822147,34322484953219,34322485084291,34322485215363\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"23.58\",\n                    \"swatchesInfo\": \"variantColor1:khaki1 ;;;; variantColor3:orange1 ;;;; variantColor2:yellow1 ;;;; variantColor5:purple1 ;;;; variantColor4:dark green1 ;;;; variantColor6:pink1 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462183_medium.jpg?v=1611184259&vid=16847225880707 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462180_medium.jpg?v=1611184260&vid=16847226011779 ;;;; variantId6:34322470600835 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462179_medium.jpg?v=1611184258&vid=16847225421955 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462182_medium.jpg?v=1611184202&vid=16847175647363 ;;;; variantId4:34322466013315 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462181_medium.jpg?v=1611184256&vid=16847225028739 ;;;; variantId5:34322468438147 ;;;; variantId2:34322460278915 ;;;; variantId3:34322463260803 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1659462178_medium.jpg?v=1611184202&vid=16847183184003 ;;;; variantId1:34322456903811 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts;;Mens Sweaters  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/couple-lovers-sweatshirts-pullover-men-women-fashion-smiley-face-printed-purple-green-justin-bieber-hoodie\",\n                    \"size\": \"XL\",\n                    \"name\": \"Couple Lovers Sweatshirts Pullover Men Women Fashion Smiley Face Printed Justin Bieber Hoodie\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: MEUGLEMENT Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts;;Mens Sweaters\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"3D\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192752988291\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"26.96\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598344_medium.jpg?v=1611184263&vid=34322474107011,34322474336387,34322474598531,34322474860675,34322482987139,34322483118211,34322483282051\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322483282051\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598366_medium.jpg?v=1611184175\",\n                    \"sku\": \"42092817-3d-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"23.92\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598344_medium.jpg?v=1611184263&vid=34322474107011,34322474336387,34322474598531,34322474860675,34322482987139,34322483118211,34322483282051\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"26.96\",\n                    \"swatchesInfo\": \"variantColor1:3D 7 ;;;; variantColor3:3D 7 ;;;; variantColor2:3D 8 ;;;; variantColor5:3D 7 ;;;; variantColor4:3D 6 ;;;; variantColor6:3D 6 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598354_medium.jpg?v=1611184251&vid=16847224012931 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598356_medium.jpg?v=1611184254&vid=16847224668291 ;;;; variantId6:34322459984003 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598358_medium.jpg?v=1611184237&vid=16847221489795 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598356_medium.jpg?v=1611184254&vid=16847224668291 ;;;; variantId4:34322456215683 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598354_medium.jpg?v=1611184251&vid=16847224012931 ;;;; variantId5:34322459492483 ;;;; variantId2:34322451628163 ;;;; variantId3:34322452775043 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1636598356_medium.jpg?v=1611184254&vid=16847224668291 ;;;; variantId1:34322448253059 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 99,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/anime-naruto-3d-hoodies-men-sweatshirts-women-autumn-hip-hop-kids-hoodie-fashion-3d-print-naruto-boys-white-and-black-pullovers\",\n                    \"size\": \"XL\",\n                    \"name\": \"Anime Naruto 3D Hoodies Men Sweatshirts Women Hip Hop Kids Hoodie Fashion 3D Print Naruto Boys And Pullovers\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Rholycrown Sleeve Length(cm): Full Style: Casual Pattern Type:\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  },\n  \"recordQueries\": [\n    {\n      \"id\": \"recsNewArrivals\",\n      \"typeOfRequest\": \"RECS_NEW_ARRIVALS\",\n      \"settings\": {\n        \"query\": {\n          \"categoryPath\": \"Women Sweatshirts\"\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ]\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  },\n  \"recordQueries\": [\n    {\n      \"id\": \"recsNewArrivals\",\n      \"typeOfRequest\": \"RECS_NEW_ARRIVALS\",\n      \"settings\": {\n        \"query\": {\n          \"categoryPath\": \"Women Sweatshirts\"\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ]\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]},\"recordQueries\":[{\"id\":\"recsNewArrivals\",\"typeOfRequest\":\"RECS_NEW_ARRIVALS\",\"settings\":{\"query\":{\"categoryPath\":\"Women Sweatshirts\"},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}]});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-158755634955912036\\\"\\n    ]\\n  },\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"recsNewArrivals\\\",\\n      \\\"typeOfRequest\\\": \\\"RECS_NEW_ARRIVALS\\\",\\n      \\\"settings\\\": {\\n        \\\"query\\\": {\\n          \\\"categoryPath\\\": \\\"Women Sweatshirts\\\"\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ]\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]},\"recordQueries\":[{\"id\":\"recsNewArrivals\",\"typeOfRequest\":\"RECS_NEW_ARRIVALS\",\"settings\":{\"query\":{\"categoryPath\":\"Women Sweatshirts\"},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}]})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "The end-point is used for retrieving new arrival product recommendations.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "new-arrivals-product-recommendations",
  "legacyHash": "ZdKDADbISBgKSJv8F1vnp"
}
```
:::

### Try it here!

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=newArrivals&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Add To Cart
[path] Guide/Analytics Tracking/

Call-to-action (CTA) buttons within the search result display, such as "Add To Cart," are essential for analytics tracking. These interactions play a crucial role in enabling machine learning algorithms to accurately rank items.

When a shopper clicks a CTA button, the resulting analytics call to Klevu should be recorded as a product click, equivalent to proceeding to the product detail page.

See the corresponding sections for the appropriate details:

- Quicksearch and Search Result product CTA  = [productTracking](https://docs.klevu.com/apis/search-events#-2qMT)
- Category page product CTA  = [categoryProductClickTracking](https://docs.klevu.com/apis/category-events#p_x2E)
- Smart Recommendations CTA  = [analytics/collect](https://docs.klevu.com/apis/recommendations-events#Ayp7W)


[title] Purchase Data
[path] Guide/Analytics Tracking/

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/productTracking",
  "name": "Reporting Single Order Data",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "klevu_apiKey",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "klevu_type",
        "type": "string",
        "description": "This is constant value. The value must be checkout."
      },
      {
        "kind": "required",
        "name": "klevu_productId",
        "type": "string",
        "description": "This is the Klevu ID of the clicked product. eg. 54321-12345."
      },
      {
        "kind": "required",
        "name": "klevu_productGroupId",
        "type": "string",
        "description": "This is the parent ID of the clicked product. eg. 54321. For compound products with a parent and multiple child/variant products, this is the common ID which ties the products together. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "required",
        "name": "klevu_productVariantId",
        "type": "string",
        "description": "This is the child/variant ID of the clicked product. eg. 12345. For compound products with a parent and multiple child/variant products, this is the ID of the specific variant. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "required",
        "name": "klevu_unit",
        "type": "Integer",
        "description": "This is the total quantity purchased. It must be an integer (e.g. 5)."
      },
      {
        "kind": "required",
        "name": "klevu_salePrice",
        "type": "Number",
        "description": "Product's sale price for one unit. You can supply decimal values. "
      },
      {
        "kind": "required",
        "name": "klevu_currency",
        "type": "string",
        "description": "Three digit currency code. e.g GBP, USD, EUR."
      },
      {
        "kind": "required",
        "name": "klevu_shopperIP",
        "type": "string",
        "description": "IP address of the shopper who bought the product(s). \n\n*If calling from javascript, this is an optional parameter."
      },
      {
        "name": "klevu_shopperIP_v4",
        "kind": "optional",
        "type": "string",
        "description": "IPv4 address of the shopper who purchased a product. ",
        "children": []
      },
      {
        "name": "klevu_shopperIP_v6",
        "kind": "optional",
        "type": "string",
        "description": "IPv6 address of the shopper who purchased a product. ",
        "children": []
      },
      {
        "name": "data_protection",
        "kind": "optional",
        "type": "Boolean",
        "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true.",
        "children": []
      },
      {
        "name": "klevu_uuid",
        "kind": "optional",
        "type": "string",
        "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid",
        "children": []
      },
      {
        "name": "klevu_country",
        "kind": "optional",
        "type": "string",
        "description": "2-digit country code of the shopper who purchased a product. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes",
        "children": []
      },
      {
        "name": "klevu_city",
        "kind": "optional",
        "type": "string",
        "description": "City name of the shopper who purchased a product.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "ewnRZCOKsK8s4PdjFvhyM",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_type=checkout&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_unit=2&klevu_salePrice=123.45&klevu_currency=GBP',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      },
      {
        "id": "EQqDeUhwCKDCWovOoWPGC",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_type=checkout&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_unit=2&klevu_salePrice=123.45&klevu_currency=GBP',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      },
      {
        "id": "8jgVxehuUIB8HJb3WWGYb",
        "code": "var xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"GET\", \"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_type=checkout&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_unit=2&klevu_salePrice=123.45&klevu_currency=GBP\");\n\nxhr.send();",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "6DGdWEWXLComG0sNANahm",
        "code": "import requests\n\nurl = \"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_type=checkout&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_unit=2&klevu_salePrice=123.45&klevu_currency=GBP\"\n\npayload={}\nheaders = {}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\nprint(response.text)\n",
        "language": "python",
        "customLabel": ""
      },
      {
        "id": "ZX8_wo0Tig8YCFpmpqeIo",
        "code": "require \"uri\"\nrequire \"net/http\"\n\nurl = URI(\"https://stats.ksearchnet.com/analytics/productTracking?klevu_apiKey=klevu-1234567890&klevu_type=checkout&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_unit=2&klevu_salePrice=123.45&klevu_currency=GBP\")\n\nhttps = Net::HTTP.new(url.host, url.port)\nhttps.use_ssl = true\n\nrequest = Net::HTTP::Get.new(url)\n\nresponse = https.request(request)\nputs response.read_body\n",
        "language": "ruby",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ewnRZCOKsK8s4PdjFvhyM"
  },
  "description": "Use this API endpoint to submit the purchase data per product.\nThe request should be made once for each line item purchased.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-single-order-data",
  "legacyHash": "ApE2ZH_SYSTjaBS9NQ9Yr"
}
```
:::



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/collect",
  "name": "Reporting Multiple Order Data (JSON)",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "event_version",
        "type": "String",
        "description": "The event version is used by Klevu's backend. The current version is 1.0.0"
      },
      {
        "kind": "required",
        "name": " event",
        "type": "string",
        "children": [],
        "description": "Define the type of event. For order, use a constant value order_purchase. "
      },
      {
        "kind": "required",
        "name": "event_apikey",
        "type": "string",
        "children": [],
        "description": "Your Klevu JS Api Key, eg. klevu-12345."
      },
      {
        "name": "event_timestamp_ms",
        "kind": "optional",
        "type": "Number",
        "description": "Event timestamp in milliseconds e.g. 1736256722349",
        "children": []
      },
      {
        "name": "user_profile",
        "kind": "required",
        "type": "Object",
        "description": "The json object that holds the user related information such as ip_address, email. ",
        "": "The json object that holds the user related information such as ip_address, email. ",
        "children": [
          {
            "name": "ip_address",
            "kind": "required",
            "type": "string",
            "description": "IP address of the shopper who purchased the product. \n"
          },
          {
            "name": "email",
            "kind": "optional",
            "type": "string",
            "description": "Email id of the shopper who purchased the product.\n"
          },
          {
            "name": "ip_address_v4",
            "kind": "optional",
            "type": "string",
            "description": "IPv4 address of the shopper who purchased a product."
          },
          {
            "name": "ip_address_v6",
            "kind": "optional",
            "type": "string",
            "description": "IPv6 address of the shopper who purchased products."
          },
          {
            "name": "data_protection",
            "kind": "optional",
            "type": "boolean",
            "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true."
          },
          {
            "name": "klevu_uuid",
            "kind": "optional",
            "type": "string",
            "description": "Universally unique identifier generated by Klevu, it can be also considered as session id."
          },
          {
            "name": "klevu_country",
            "kind": "optional",
            "type": "string",
            "description": "2-digit country code of the shopper who purchased products. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes"
          },
          {
            "name": "klevu_city",
            "kind": "optional",
            "type": "string",
            "description": "City name of the shopper who purchased products."
          }
        ],
        "schema": [
          {
            "name": "ip_address",
            "kind": "required",
            "type": "string",
            "description": "IP address of the shopper who purchased the product. \n"
          },
          {
            "name": "email",
            "kind": "optional",
            "type": "string",
            "description": "Email id of the shopper who purchased the product.\n"
          },
          {
            "name": "ip_address_v4",
            "kind": "optional",
            "type": "string",
            "description": "IPv4 address of the shopper who purchased a product."
          },
          {
            "name": "ip_address_v6",
            "kind": "optional",
            "type": "string",
            "description": "IPv6 address of the shopper who purchased products."
          },
          {
            "name": "data_protection",
            "kind": "optional",
            "type": "boolean",
            "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true."
          },
          {
            "name": "klevu_uuid",
            "kind": "optional",
            "type": "string",
            "description": "Universally unique identifier generated by Klevu, it can be also considered as session id."
          },
          {
            "name": "klevu_country",
            "kind": "optional",
            "type": "string",
            "description": "2-digit country code of the shopper who purchased products. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes"
          },
          {
            "name": "klevu_city",
            "kind": "optional",
            "type": "string",
            "description": "City name of the shopper who purchased products."
          }
        ]
      },
      {
        "kind": "required",
        "name": "items",
        "type": "Array",
        "children": [],
        "description": "Depending on the number of orders, the item array accepts single or more orders.  "
      },
      {
        "kind": "optional",
        "name": "order_id",
        "type": "string",
        "children": [],
        "description": "The unique identifier for your orders. "
      },
      {
        "kind": "optional",
        "name": "order_line_id",
        "type": "string",
        "children": [],
        "description": "The unique identifier for reference to a line on an order within the database. "
      },
      {
        "kind": "required",
        "name": "item_name",
        "type": "string",
        "children": [],
        "description": "The name of the product."
      },
      {
        "kind": "required",
        "name": "item_id",
        "type": "string",
        "children": [],
        "description": "The full ID of the product. eg. 12345-54321. This will match the unique value used in your data sync process with Klevu. For compound products consisting of a child/variant and a parent, this is usually parentId-childId."
      },
      {
        "kind": "required",
        "name": "item_group_id",
        "type": "string",
        "children": [],
        "description": "The Parent ID of the product. eg. 12345. For compound products consisting of a child/variant and a parent, please specify the ID of the parent. For simple products, please re-use the same value as item_id"
      },
      {
        "kind": "required",
        "name": "item_variant_id",
        "type": "string",
        "children": [],
        "description": "The Child ID of the product.eg. 54321. Please specify the ID of the child/variant product. For simple products, please re-use the same value as item_id."
      },
      {
        "kind": "required",
        "name": "unit_price",
        "type": "Number",
        "children": [],
        "description": "The final selling price of the product, for example 123.45"
      },
      {
        "kind": "required",
        "name": "currency",
        "type": "string",
        "children": [],
        "description": "The currency of the above price, eg. USD."
      },
      {
        "kind": "optional",
        "name": "units",
        "type": "Integer",
        "children": [],
        "description": "The number of units sold for a product. In case if the parameter is mising, the default value will be 1 "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "FI7DVhQck3_P270nihiHK",
        "code": "",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "FI7DVhQck3_P270nihiHK"
  },
  "examples": {
    "languages": [
      {
        "id": "DjsRpQrxfQsrjFNj4P-wd",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/collect',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'[\n    {\n        \"event\": \"order_purchase\",\n        \"event_apikey\": \"klevu-12345\",\n        \"user_profile\" : {\n           \"ip_address\":\"111.11.11.1\",\n           \"email\":\"user@klevu.com\"\n        },\n        \"event_version\": \"1.0.0\",\n        \"event_data\": {\n            \"items\": [\n                {\n                    \"order_id\": \"1223434\",\n                    \"order_line_id\": \"ABC-12343\",\n                    \"item_name\": \"45RU,800x1070,N-Type,D,NoS,CM,WH,EA\",\n                    \"item_id\": \"75882\",\n                    \"item_group_id\": \"75882\",\n                    \"item_variant_id\": \"75882\",\n                    \"unit_price\": 6033.42,\n                    \"currency\": \"USD\",\n                    \"units\": 2\n                },\n                {\n                    \"order_id\": \"1223435\",\n                    \"order_line_id\": \"ABC-12344\",\n                    \"item_name\": \"NoS,CM,WH,EA\",\n                    \"item_id\": \"75883\",\n                    \"item_group_id\": \"75883\",\n                    \"item_variant_id\": \"75883\",\n                    \"unit_price\": 6033.42,\n                    \"currency\": \"US\",\n                    \"units\": 1\n                }\n            ]\n        }\n    }\n]',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "EDjoAAR2ZByzaLdipyefN",
        "code": "// WARNING: For POST requests, body is set to null by browsers.\nvar data = JSON.stringify([\n  {\n    \"event\": \"order_purchase\",\n    \"event_apikey\": \"klevu-12345\",\n    \"user_profile\" : {\n           \"ip_address\":\"111.11.11.1\",\n           \"email\":\"user@klevu.com\"\n    },\n    \"event_version\": \"1.0.0\",\n    \"event_data\": {\n      \"items\": [\n        {\n          \"order_id\": \"1223434\",\n          \"order_line_id\": \"ABC-12343\",\n          \"item_name\": \"45RU,800x1070,N-Type,D,NoS,CM,WH,EA\",\n          \"item_id\": \"75882\",\n          \"item_group_id\": \"75882\",\n          \"item_variant_id\": \"75882\",\n          \"unit_price\": 6033.42,\n          \"currency\": \"CAD\",\n          \"units\": 2\n        }\n      ]\n    }\n  }\n]);\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://stats.ksearchnet.com/analytics/collect\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "ZZuMafHLxj_2bRMNg3sSL",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"[\\n    {\\n        \\\"event\\\": \\\"order_purchase\\\",\\n        \\\"event_apikey\\\": \\\"klevu-12345\\\",\\n        \\\"event_version\\\": \\\"1.0.0\\\",\\n        \\\"event_data\\\": {\\n            \\\"items\\\": [\\n                {\\n                    \\\"order_id\\\": \\\"1223434\\\",\\n                    \\\"order_line_id\\\": \\\"ABC-12343\\\",\\n                    \\\"item_name\\\": \\\"45RU,800x1070,N-Type,D,NoS,CM,WH,EA\\\",\\n                    \\\"item_id\\\": \\\"75882\\\",\\n                    \\\"item_group_id\\\": \\\"75882\\\",\\n                    \\\"item_variant_id\\\": \\\"75882\\\",\\n                    \\\"unit_price\\\": 6033.42,\\n                    \\\"currency\\\": \\\"CAD\\\",\\n                    \\\"units\\\": 2\\n                }\\n            ]\\n        }\\n    }\\n]\");\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/collect\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "d8aE_l0VU6R3vBKtka0iZ",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://stats.ksearchnet.com/analytics/collect',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify([\n    {\n      \"event\": \"order_purchase\",\n      \"event_apikey\": \"klevu-1234\",\n      \"user_profile\" : {\n           \"ip_address\":\"111.11.11.1\",\n           \"email\":\"user@klevu.com\"\n      },\n      \"event_version\": \"1.0.0\",\n      \"event_data\": {\n        \"items\": [\n          {\n            \"order_id\": \"1223434\",\n            \"order_line_id\": \"ABC-12343\",\n            \"item_name\": \"45RU,800x1070,N-Type,D,NoS,CM,WH,EA\",\n            \"item_id\": \"75882\",\n            \"item_group_id\": \"75882\",\n            \"item_variant_id\": \"75882\",\n            \"unit_price\": 6033.42,\n            \"currency\": \"CAD\",\n            \"units\": 2\n          }\n        ]\n      }\n    }\n  ])\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DjsRpQrxfQsrjFNj4P-wd"
  },
  "description": "The end-point is used for reporting multiple orders in batch.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-multiple-order-data-json",
  "legacyHash": "1mbNqPgyf_8tnxUqaldk8"
}
```
:::




[title] Recommendations Events
[path] Guide/Analytics Tracking/



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/collect",
  "name": "Reporting Recommendation Impressions",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "event",
        "type": "string",
        "description": "Please use view_recs_list"
      },
      {
        "kind": "required",
        "name": "event_apikey\t",
        "type": "string",
        "description": "Your Klevu JS Api Key, eg. klevu-12345."
      },
      {
        "kind": "required",
        "name": "event_list_id",
        "type": "string",
        "description": "The unique identifier for your KMC Recommendations Banner, eg. 12345-abcde. This is available in the banner configuration metadata as recsKey. If you are not using banners configured within the KMC, please specify a unique identifier for the banner which will be used to distinguish one banner from another."
      },
      {
        "kind": "required",
        "name": "event_list_name",
        "type": "string",
        "description": "The name of the banner, eg. New Arrivals. This is available in the banner configuration metadata as title"
      },
      {
        "kind": "required",
        "name": "event_list_logic",
        "type": "string",
        "description": "The logic type of the banner, eg. NEWEST_ARRIVALS. This is available in the banner configuration metadata as logic."
      },
      {
        "kind": "optional",
        "name": "event_tags",
        "type": "Array",
        "description": "This can be used to specify additional information about the event, which will eventually be made available within the KMC. We recommend you specify the type of page, eg. HOME. This is available in the banner configuration metadata as pageType."
      },
      {
        "name": "user_profile",
        "kind": "required",
        "type": "Object",
        "description": "The json object that holds the user related information such as ip_address. ",
        "children": [
          {
            "name": "ip_address",
            "kind": "required",
            "type": "string",
            "description": "IP address of the shopper who viewed the event \n\n*If calling from javascript, this is an optional parameter."
          },
          {
            "name": "ip_address_v4",
            "kind": "optional",
            "type": "string",
            "description": "IPv4 address of the shopper who viewed a product."
          },
          {
            "name": "ip_address_v6",
            "kind": "optional",
            "type": "string",
            "description": "IPv6 address of the shopper who viewed a product."
          },
          {
            "name": "data_protection",
            "kind": "optional",
            "type": "Boolean",
            "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true."
          },
          {
            "name": "klevu_uuid",
            "kind": "optional",
            "type": "string",
            "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid"
          },
          {
            "name": "klevu_country",
            "kind": "optional",
            "type": "string",
            "description": "2-digit country code of the shopper who viewed a product. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes"
          },
          {
            "name": "klevu_city",
            "kind": "optional",
            "type": "string",
            "description": "City name of the shopper who viewed a product."
          }
        ]
      },
      {
        "kind": "required",
        "name": "items",
        "type": "Array",
        "description": "Iterate all of the products in the banner and populate the item data for each."
      },
      {
        "kind": "required",
        "name": "item_id",
        "type": "string",
        "description": "The full ID of the product. eg. 12345-54321. This will match the unique value used in your data sync process with Klevu. For compound products consisting of a child/variant and a parent, this is usually parentId-childId."
      },
      {
        "kind": "required",
        "name": "item_group_id",
        "type": "string",
        "description": "The Parent ID of the product. eg. 12345. For compound products consisting of a child/variant and a parent, please specify the ID of the parent. For simple products, please re-use the same value as item_id"
      },
      {
        "kind": "required",
        "name": "item_variant_id",
        "type": "string",
        "description": "The Child ID of the product.eg. 54321. Please specify the ID of the child/variant product. For simple products, please re-use the same value as item_id."
      },
      {
        "kind": "required",
        "name": "item_name",
        "type": "string",
        "description": "The name of the product."
      },
      {
        "kind": "required",
        "name": "price",
        "type": "Number",
        "description": "The final selling price of the product, for example 123.45"
      },
      {
        "kind": "optional",
        "name": "currency",
        "type": "string",
        "description": "The currency of the above price, eg. USD."
      },
      {
        "kind": "optional",
        "name": "item_brand",
        "type": "string",
        "description": "The brand of the product, for example \"Nike\" or \"Acme\"."
      },
      {
        "kind": "optional",
        "name": "item_category",
        "type": "string",
        "description": "The category the item belongs to. For nested categories, use the ; character to separate the hierarchy, and for multiple categories use a double ;;. For example, for 'Mens > Shoes > Trainers' and 'Sale' you would specify: Mens;Shoes;Trainers;;Sale."
      },
      {
        "kind": "required",
        "name": "index",
        "type": "Integer",
        "description": "The order of the product in the listing, starting from 1"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "FI7DVhQck3_P270nihiHK",
        "code": "",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "FI7DVhQck3_P270nihiHK"
  },
  "examples": {
    "languages": [
      {
        "id": "DjsRpQrxfQsrjFNj4P-wd",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/collect',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'[\n  {\n    \"event\": \"view_recs_list\",\n    \"event_apikey\": \"klevu-12345\",\n    \"event_list_id\": \"12345-abcde\",\n    \"event_tags\": [\n      \"recsPageType:category\"\n    ],\n    \"event_list_name\": \"New Arrivals\",\n    \"event_list_logic\": \"NEWEST_ARRIVALS\",\n    \"user_profile\" : {\n       \"ip_address\":\"111.11.11.1\"\n    },\n    \"items\": [\n      {\n        \"item_id\": \"12345-54321\",\n        \"item_group_id\": \"12345\",\n        \"item_variant_id\": \"54321\",\n        \"item_name\": \"Hoodie Sweatshirt\",\n        \"price\": \"123.45\",\n        \"currency\": \"GBP\",\n        \"item_brand\": \"Acme\",\n        \"item_category\": \"All;;Coats & Jackets;;Womens Coats\",\n        \"index\": 1\n      }\n    ]\n  },\n  {\n    \"event\": \"select_recs_list\",\n    \"event_apikey\": \"klevu-12345\",\n    \"event_list_id\": \"12345-abcde\",\n    \"event_tags\": [\n      \"recsPageType:category\"\n    ],\n    \"event_list_name\": \"New Arrivals\",\n    \"event_list_logic\": \"NEWEST_ARRIVALS\",\n    \"user_profile\" : {\n       \"ip_address\":\"111.11.11.1\"\n    },\n    \"items\": [\n      {\n        \"item_id\": \"12345-54321\",\n        \"item_group_id\": \"12345\",\n        \"item_variant_id\": \"54321\",\n        \"item_name\": \"Hoodie Sweatshirt\",\n        \"price\": \"123.45\",\n        \"currency\": \"GBP\",\n        \"item_brand\": \"Acme\",\n        \"item_category\": \"All;;Coats & Jackets;;Womens Coats\",\n        \"index\": 1\n      }\n    ]\n  }\n]',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "EDjoAAR2ZByzaLdipyefN",
        "code": "var data = JSON.stringify([{\"event\":\"view_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"user_profile\" : {\"ip_address\":\"111.11.11.1\"},\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]},{\"event\":\"select_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]}]);\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://stats.ksearchnet.com/analytics/collect\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "ZZuMafHLxj_2bRMNg3sSL",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"[\\n  {\\n    \\\"event\\\": \\\"view_recs_list\\\",\\n    \\\"event_apikey\\\": \\\"klevu-12345\\\",\\n    \\\"event_list_id\\\": \\\"12345-abcde\\\",\\n    \\\"event_tags\\\": [\\n      \\\"recsPageType:category\\\"\\n    ],\\n    \\\"event_list_name\\\": \\\"New Arrivals\\\",\\n    \\\"event_list_logic\\\": \\\"NEWEST_ARRIVALS\\\",\\n \\\"user_profile\\\" : {\\\"ip_address\\\":\\\"111.11.11.1\\\"},\\n   \\\"items\\\": [\\n      {\\n        \\\"item_id\\\": \\\"12345-54321\\\",\\n        \\\"item_group_id\\\": \\\"12345\\\",\\n        \\\"item_variant_id\\\": \\\"54321\\\",\\n        \\\"item_name\\\": \\\"Hoodie Sweatshirt\\\",\\n        \\\"price\\\": \\\"123.45\\\",\\n        \\\"currency\\\": \\\"GBP\\\",\\n        \\\"item_brand\\\": \\\"Acme\\\",\\n        \\\"item_category\\\": \\\"All;;Coats & Jackets;;Womens Coats\\\",\\n        \\\"index\\\": 1\\n      }\\n    ]\\n  },\\n  {\\n    \\\"event\\\": \\\"select_recs_list\\\",\\n    \\\"event_apikey\\\": \\\"klevu-12345\\\",\\n    \\\"event_list_id\\\": \\\"12345-abcde\\\",\\n    \\\"event_tags\\\": [\\n      \\\"recsPageType:category\\\"\\n    ],\\n    \\\"event_list_name\\\": \\\"New Arrivals\\\",\\n    \\\"event_list_logic\\\": \\\"NEWEST_ARRIVALS\\\",\\n    \\\"items\\\": [\\n      {\\n        \\\"item_id\\\": \\\"12345-54321\\\",\\n        \\\"item_group_id\\\": \\\"12345\\\",\\n        \\\"item_variant_id\\\": \\\"54321\\\",\\n        \\\"item_name\\\": \\\"Hoodie Sweatshirt\\\",\\n        \\\"price\\\": \\\"123.45\\\",\\n        \\\"currency\\\": \\\"GBP\\\",\\n        \\\"item_brand\\\": \\\"Acme\\\",\\n        \\\"item_category\\\": \\\"All;;Coats & Jackets;;Womens Coats\\\",\\n        \\\"index\\\": 1\\n      }\\n    ]\\n  }\\n]\");\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/collect\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "d8aE_l0VU6R3vBKtka0iZ",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://stats.ksearchnet.com/analytics/collect',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify([{\"event\":\"view_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"user_profile\" : {\"ip_address\":\"111.11.11.1\"},\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]},{\"event\":\"select_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]}])\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "EDjoAAR2ZByzaLdipyefN"
  },
  "description": "The end-point is used for reporting banner product views.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-recommendation-impressions",
  "legacyHash": "q0cVebk74VInhU0RI1pwU"
}
```
:::



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/collect",
  "name": "Reporting Banner Product Clicks",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "event",
        "type": "string",
        "description": "Please use select_recs_list"
      },
      {
        "kind": "required",
        "name": "event_apikey\t",
        "type": "string",
        "description": "Your Klevu JS Api Key, eg. klevu-12345."
      },
      {
        "kind": "required",
        "name": "event_list_id",
        "type": "string",
        "description": "The unique identifier for your KMC Recommendations Banner, eg. 12345-abcde. This is available in the banner configuration metadata as recsKey. If you are not using banners configured within the KMC, please specify a unique identifier for the banner which will be used to distinguish one banner from another."
      },
      {
        "kind": "required",
        "name": "event_list_name",
        "type": "string",
        "description": "The name of the banner, eg. New Arrivals. This is available in the banner configuration metadata as title"
      },
      {
        "kind": "required",
        "name": "event_list_logic",
        "type": "string",
        "description": "The logic type of the banner, eg. NEWEST_ARRIVALS. This is available in the banner configuration metadata as logic."
      },
      {
        "kind": "optional",
        "name": "event_tags",
        "type": "Array",
        "description": "This can be used to specify additional information about the event, which will eventually be made available within the KMC. We recommend you specify the type of page, eg. HOME. This is available in the banner configuration metadata as pageType."
      },
      {
        "name": "user_profile",
        "kind": "required",
        "type": "Object",
        "description": "The json object that holds the user related information such as ip_address. ",
        "children": [
          {
            "name": "ip_address",
            "kind": "required",
            "type": "string",
            "description": "IP address of the shopper who purchased the product. \n\n*If calling from javascript, this is an optional parameter."
          },
          {
            "name": "ip_address_v4",
            "kind": "optional",
            "type": "string",
            "description": "IPv4 address of the shopper who viewed a product."
          },
          {
            "name": "ip_address_v6",
            "kind": "optional",
            "type": "string",
            "description": "IPv6 address of the shopper who viewed a product."
          },
          {
            "name": "data_protection",
            "kind": "optional",
            "type": "Boolean",
            "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true."
          },
          {
            "name": "klevu_uuid",
            "kind": "optional",
            "type": "string",
            "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid"
          },
          {
            "name": "klevu_country",
            "kind": "optional",
            "type": "string",
            "description": "2-digit country code of the shopper who viewed a product. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes"
          },
          {
            "name": "klevu_city",
            "kind": "optional",
            "type": "string",
            "description": "City name of the shopper who viewed a product."
          }
        ]
      },
      {
        "kind": "required",
        "name": "items",
        "type": "Array",
        "description": "Provide specific information about the one product which was clicked within your banner."
      },
      {
        "kind": "required",
        "name": "item_id",
        "type": "string",
        "description": "The full ID of the product. eg. 12345-54321. This will match the unique value used in your data sync process with Klevu. For compound products consisting of a child/variant and a parent, this is usually parentId-childId."
      },
      {
        "kind": "required",
        "name": "item_group_id",
        "type": "string",
        "description": "The Parent ID of the product. eg. 12345. For compound products consisting of a child/variant and a parent, please specify the ID of the parent. For simple products, please re-use the same value as item_id"
      },
      {
        "kind": "required",
        "name": "item_variant_id",
        "type": "string",
        "description": "The Child ID of the product.eg. 54321. Please specify the ID of the child/variant product. For simple products, please re-use the same value as item_id."
      },
      {
        "kind": "required",
        "name": "item_name",
        "type": "string",
        "description": "The name of the product."
      },
      {
        "kind": "required",
        "name": "price",
        "type": "Number",
        "description": "The final selling price of the product, for example 123.45"
      },
      {
        "kind": "optional",
        "name": "currency",
        "type": "string",
        "description": "The currency of the above price, eg. USD."
      },
      {
        "kind": "optional",
        "name": "item_brand",
        "type": "string",
        "description": "The brand of the product, for example \"Nike\" or \"Acme\"."
      },
      {
        "kind": "optional",
        "name": "item_category",
        "type": "string",
        "description": "The category the item belongs to. For nested categories, use the ; character to separate the hierarchy, and for multiple categories use a double ;;. For example, for 'Mens > Shoes > Trainers' and 'Sale' you would specify: Mens;Shoes;Trainers;;Sale."
      },
      {
        "kind": "required",
        "name": "index",
        "type": "Integer",
        "description": "The order of the product in the listing, starting from 1"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "FI7DVhQck3_P270nihiHK",
        "code": "",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "FI7DVhQck3_P270nihiHK"
  },
  "examples": {
    "languages": [
      {
        "id": "DjsRpQrxfQsrjFNj4P-wd",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/collect',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'[\n  {\n    \"event\": \"view_recs_list\",\n    \"event_apikey\": \"klevu-12345\",\n    \"event_list_id\": \"12345-abcde\",\n    \"event_tags\": [\n      \"recsPageType:category\"\n    ],\n    \"event_list_name\": \"New Arrivals\",\n    \"event_list_logic\": \"NEWEST_ARRIVALS\",\n    \"user_profile\" : {\n       \"ip_address\":\"111.11.11.1\"\n    },\n    \"items\": [\n      {\n        \"item_id\": \"12345-54321\",\n        \"item_group_id\": \"12345\",\n        \"item_variant_id\": \"54321\",\n        \"item_name\": \"Hoodie Sweatshirt\",\n        \"price\": \"123.45\",\n        \"currency\": \"GBP\",\n        \"item_brand\": \"Acme\",\n        \"item_category\": \"All;;Coats & Jackets;;Womens Coats\",\n        \"index\": 1\n      }\n    ]\n  },\n  {\n    \"event\": \"select_recs_list\",\n    \"event_apikey\": \"klevu-12345\",\n    \"event_list_id\": \"12345-abcde\",\n    \"event_tags\": [\n      \"recsPageType:category\"\n    ],\n    \"event_list_name\": \"New Arrivals\",\n    \"event_list_logic\": \"NEWEST_ARRIVALS\",\n    \"user_profile\" : {\n       \"ip_address\":\"111.11.11.1\"\n    },\n    \"items\": [\n      {\n        \"item_id\": \"12345-54321\",\n        \"item_group_id\": \"12345\",\n        \"item_variant_id\": \"54321\",\n        \"item_name\": \"Hoodie Sweatshirt\",\n        \"price\": \"123.45\",\n        \"currency\": \"GBP\",\n        \"item_brand\": \"Acme\",\n        \"item_category\": \"All;;Coats & Jackets;;Womens Coats\",\n        \"index\": 1\n      }\n    ]\n  }\n]',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "EDjoAAR2ZByzaLdipyefN",
        "code": "var data = JSON.stringify([{\"event\":\"view_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"user_profile\" : {\"ip_address\":\"111.11.11.1\"},\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]},{\"event\":\"select_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]}]);\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://stats.ksearchnet.com/analytics/collect\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "ZZuMafHLxj_2bRMNg3sSL",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"[\\n  {\\n    \\\"event\\\": \\\"view_recs_list\\\",\\n    \\\"event_apikey\\\": \\\"klevu-12345\\\",\\n    \\\"event_list_id\\\": \\\"12345-abcde\\\",\\n    \\\"event_tags\\\": [\\n      \\\"recsPageType:category\\\"\\n    ],\\n    \\\"event_list_name\\\": \\\"New Arrivals\\\",\\n    \\\"event_list_logic\\\": \\\"NEWEST_ARRIVALS\\\",\\n \\\"user_profile\\\" : {\\\"ip_address\\\":\\\"111.11.11.1\\\"},\\n   \\\"items\\\": [\\n      {\\n        \\\"item_id\\\": \\\"12345-54321\\\",\\n        \\\"item_group_id\\\": \\\"12345\\\",\\n        \\\"item_variant_id\\\": \\\"54321\\\",\\n        \\\"item_name\\\": \\\"Hoodie Sweatshirt\\\",\\n        \\\"price\\\": \\\"123.45\\\",\\n        \\\"currency\\\": \\\"GBP\\\",\\n        \\\"item_brand\\\": \\\"Acme\\\",\\n        \\\"item_category\\\": \\\"All;;Coats & Jackets;;Womens Coats\\\",\\n        \\\"index\\\": 1\\n      }\\n    ]\\n  },\\n  {\\n    \\\"event\\\": \\\"select_recs_list\\\",\\n    \\\"event_apikey\\\": \\\"klevu-12345\\\",\\n    \\\"event_list_id\\\": \\\"12345-abcde\\\",\\n    \\\"event_tags\\\": [\\n      \\\"recsPageType:category\\\"\\n    ],\\n    \\\"event_list_name\\\": \\\"New Arrivals\\\",\\n    \\\"event_list_logic\\\": \\\"NEWEST_ARRIVALS\\\",\\n    \\\"items\\\": [\\n      {\\n        \\\"item_id\\\": \\\"12345-54321\\\",\\n        \\\"item_group_id\\\": \\\"12345\\\",\\n        \\\"item_variant_id\\\": \\\"54321\\\",\\n        \\\"item_name\\\": \\\"Hoodie Sweatshirt\\\",\\n        \\\"price\\\": \\\"123.45\\\",\\n        \\\"currency\\\": \\\"GBP\\\",\\n        \\\"item_brand\\\": \\\"Acme\\\",\\n        \\\"item_category\\\": \\\"All;;Coats & Jackets;;Womens Coats\\\",\\n        \\\"index\\\": 1\\n      }\\n    ]\\n  }\\n]\");\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/collect\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "d8aE_l0VU6R3vBKtka0iZ",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://stats.ksearchnet.com/analytics/collect',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify([{\"event\":\"view_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"user_profile\" : {\"ip_address\":\"111.11.11.1\"},\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]},{\"event\":\"select_recs_list\",\"event_apikey\":\"klevu-12345\",\"event_list_id\":\"12345-abcde\",\"event_tags\":[\"recsPageType:category\"],\"event_list_name\":\"New Arrivals\",\"event_list_logic\":\"NEWEST_ARRIVALS\",\"items\":[{\"item_id\":\"12345-54321\",\"item_group_id\":\"12345\",\"item_variant_id\":\"54321\",\"item_name\":\"Hoodie Sweatshirt\",\"price\":\"123.45\",\"currency\":\"GBP\",\"item_brand\":\"Acme\",\"item_category\":\"All;;Coats & Jackets;;Womens Coats\",\"index\":1}]}])\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ZZuMafHLxj_2bRMNg3sSL"
  },
  "description": "The end-point is used for reporting banner product clicks.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-banner-product-clicks",
  "legacyHash": "Ayp7W8joTUfB8QxVxgzhl"
}
```
:::




[title] Smart Search
[path] Guide/

Klevu Smart Search is underpinned by deep research into Machine Learning and Linguistics. But, the best part? It’s super easy to install and requires almost no maintenance to deliver phenomenal ROI.

Use Klevu's search APIs to build your own search experience.&#x20;

## Getting Started

Understanding Klevu's API [Overview](docId\:cZeodl0sKcuv-18IPupLr) format and prerequisites.

- Predict typeahead  [Search as you type](docId\:nnhyHzYF6_QqoVvxZJNM_)&#x20;
- Multiple [Record search](docId\:Zc0muJI48jU_b3yX42NOo) queries within a single HTTP request.
- Automatic aggregation of data to use as  [Faceting](docId\:jnoK0xcgZMzyszVQjCCcb)&#x20;
- [Personalisation](docId\:YFU114Puw2lTVF05GaFWv) results based on your customer's preferences.
- Explore known scenarios and [Examples](docId\:wsXhoshW0Gl78gJhvLYI7)&#x20;
- Integrate  [Analytics Events](docId\:MjUDl2Y9O5YbYRM00HWmF)&#x20;


[title] Search as you type
[path] Guide/Smart Search/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

The suggestions object is used for fetching autocomplete suggestions. This allows you to try and **predict** what the customer might be looking for and propose relevant search queries applicable to your catalog.

For example when the customer starts typing "a", Klevu can start **making suggestions**. For example it may suggest some terms starting with the letter "a" like "arris desk". It may also suggest terms not starting with "a" such as "black arris desk".

The Klevu suggestions are **error tolerant**, e.g. "fairry lights" would find suggestions for "fairy lights", and also **order tolerant**, e.g. "lights fairy" would find suggestions for "fairy lights".

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{hostname}}/cs/v2/search",
  "name": "Instant auto complete",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "id",
        "type": "string",
        "description": "Every suggestion request must have a unique identifier associated with it. When a result is retrieved, the ID of each query is associated with it's respective response."
      },
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "string",
        "description": "This parameter defines the type of request. Specify 'AUTO_SUGGESTIONS' for typeahead autosuggestion predictions."
      },
      {
        "kind": "required",
        "name": "query",
        "type": "string",
        "description": "The search term or phrase for which the suggestions are retrieved from Klevu Search."
      },
      {
        "kind": "optional",
        "name": "hlStartElem",
        "type": "string",
        "description": "By default, the section of an autosuggestion matching what the customer has typed is highlighted in bold using values of '<b>' and </b>'. If you prefer something else, you can override these values with your own HTML."
      },
      {
        "kind": "optional",
        "name": "hlEndElem",
        "type": "string",
        "description": "By default, the section of an autosuggestion matching what the customer has typed is highlighted in bold using values of '<b>' and </b>'. If you prefer something else, you can override these values with your own HTML."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 24,\n        \"responseCode\": 200\n    },\n    \"suggestionResults\": [\n        {\n            \"id\": \"mySuggestionsQuery1\",\n            \"suggestions\": [\n                {\n                    \"suggest\": \"sweatshirt\"\n                },\n                {\n                    \"suggest\": \"street sweatshirt\"\n                }\n            ]\n        },\n        {\n            \"id\": \"mySuggestionsQuery2\",\n            \"suggestions\": [\n                {\n                    \"suggest\": \"<span style='color:red'>short</span>\"\n                },\n                {\n                    \"suggest\": \"<span style='color:red'>short</span>s\"\n                },\n                {\n                    \"suggest\": \"<span style='color:red'>short</span>-sleeve\"\n                }\n            ]\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"suggestions\": [\n    {\n      \"id\": \"mySuggestionsQuery1\",\n      \"typeOfRequest\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"shirt\",\n      \"limit\": 2\n    },\n    {\n      \"id\": \"mySuggestionsQuery2\",\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"short\",\n      \"limit\": 3,\n      \"hlStartElem\": \"<span style='color:red'>\",\n      \"hlEndElem\": \"</span>\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "SCsTjoapS-0-uf4KJtHCj",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"suggestions\": [\n    {\n      \"id\": \"mySuggestionsQuery1\",\n      \"typeOfRequest\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"shirt\",\n      \"limit\": 2\n    },\n    {\n      \"id\": \"mySuggestionsQuery2\",\n      \"typeOfRequest\": \"AUTO_SUGGESTIONS\",\n      \"query\": \"short\",\n      \"limit\": 3,\n      \"hlStartElem\": \"<span style=\\'color:red\\'>\",\n      \"hlEndElem\": \"</span>\"\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-156925593843210765\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: text/plain'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "EbXKm6hQoHGHMh1EAhNmw",
        "code": "var data = \"{\\n  \\\"suggestions\\\": [\\n    {\\n      \\\"id\\\": \\\"mySuggestionsQuery1\\\",\\n      \\\"typeOfRequest\\\": \\\"AUTO_SUGGESTIONS\\\",\\n      \\\"query\\\": \\\"shirt\\\",\\n      \\\"limit\\\": 2\\n    },\\n    {\\n      \\\"id\\\": \\\"mySuggestionsQuery2\\\",\\n      \\\"typeOfQuery\\\": \\\"AUTO_SUGGESTIONS\\\",\\n      \\\"query\\\": \\\"short\\\",\\n      \\\"limit\\\": 3,\\n      \\\"hlStartElem\\\": \\\"<span style='color:red'>\\\",\\n      \\\"hlEndElem\\\": \\\"</span>\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\";\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs15v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"text/plain\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "qvlH3fSg-r8UBEAurxbOD",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"text/plain\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"suggestions\\\": [\\n    {\\n      \\\"id\\\": \\\"mySuggestionsQuery1\\\",\\n      \\\"typeOfRequest\\\": \\\"AUTO_SUGGESTIONS\\\",\\n      \\\"query\\\": \\\"shirt\\\",\\n      \\\"limit\\\": 2\\n    },\\n    {\\n      \\\"id\\\": \\\"mySuggestionsQuery2\\\",\\n      \\\"typeOfQuery\\\": \\\"AUTO_SUGGESTIONS\\\",\\n      \\\"query\\\": \\\"short\\\",\\n      \\\"limit\\\": 3,\\n      \\\"hlStartElem\\\": \\\"<span style='color:red'>\\\",\\n      \\\"hlEndElem\\\": \\\"</span>\\\"\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-156925593843210765\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs15v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"text/plain\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "_D8z-JNrIkf8f0KTEcMOz",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs15v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'text/plain'\n  },\n  body: '{\\n  \"suggestions\": [\\n    {\\n      \"id\": \"mySuggestionsQuery1\",\\n      \"typeOfRequest\": \"AUTO_SUGGESTIONS\",\\n      \"query\": \"shirt\",\\n      \"limit\": 2\\n    },\\n    {\\n      \"id\": \"mySuggestionsQuery2\",\\n      \"typeOfQuery\": \"AUTO_SUGGESTIONS\",\\n      \"query\": \"short\",\\n      \"limit\": 3,\\n      \"hlStartElem\": \"<span style=\\'color:red\\'>\",\\n      \"hlEndElem\": \"</span>\"\\n    }\\n  ],\\n  \"context\": {\\n    \"apiKeys\": [\\n      \"klevu-156925593843210765\"\\n    ]\\n  }\\n}'\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "SCsTjoapS-0-uf4KJtHCj"
  },
  "description": "This is an example to fetch instant auto complete using APIs.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "instant-auto-complete",
  "legacyHash": "YX-Yxs_890rjZ7cyoPNtS"
}
```
:::

### Try it here!&#x20;

:::Iframe{iframeHeight="0" code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?codemirror=1&fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=searchAsYouType&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>"}

:::







[title] Banners
[path] Guide/Dashboard Settings/

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://js.klevu.com/klevu-js-v1/klevu-js-api/{{JS_API_KEY}}-banner.json",
  "name": "Banners",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "JS_API_KEY",
        "type": "string",
        "description": "Your public Klevu JS API Key.\n"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "Y1Vx38kZQPtiLmsufAFM_",
        "code": "{\n    \"klevu_banner\": [\n        {\n            \"showForTerms\": null,\n            \"showOnLandingPage\": true,\n            \"redirectUrl\": \"https://demo.ksearchmisc.com/klevusearch/home-decor.html\",\n            \"showOnQuickSearch\": true,\n            \"endDate\": \"2021/08/18\",\n            \"bannerName\": \"disney plus\",\n            \"position\": \"bottom\",\n            \"bannerRef\": 8840,\n            \"bannerImg\": \"https://www.denofgeek.com/wp-content/uploads/2019/11/disney-plus-free-trial-banner.jpg\",\n            \"showOnCategoryPage\": false,\n            \"startDate\": \"2021/8/17\"\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Y1Vx38kZQPtiLmsufAFM_"
  },
  "examples": {
    "languages": [
      {
        "id": "3AdeysJML2Tq9WYHSdiJU",
        "code": "curl --location --request GET 'https://js.klevu.com/klevu-js-v1/klevu-js-api/klevu-1234567890-banner.json'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3AdeysJML2Tq9WYHSdiJU"
  },
  "description": "This API call uses a simple GET request with no payload, and since it is intended for use on the frontend there is no authentication required.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "banners",
  "legacyHash": "uFN0pI-f3BZCXFZPdr81Q"
}
```
:::

:::ApiMethodV2
```json
{
  "name": "Reporting Banner Click events",
  "method": "GET",
  "url": "https://stats.ksearchnet.com/analytics/dataTracking",
  "description": "Utilize the following API endpoint to submit the click events for banners.",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "bpv9nSMp-jaFwIOZwzLSf",
        "language": "curl",
        "code": "curl --location --request GET 'https://stats.ksearchnet.com/analytics/dataTracking?klevu_term=tee&klevu_bannerId=12463&klevu_image=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_target=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_request=click&type=banner&klevu_apiKey=klevu-1234567890'",
        "customLabel": ""
      },
      {
        "id": "THP_oY0XLPmn0q_UnK_Wn",
        "language": "php",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/dataTracking?klevu_term=tee&klevu_bannerId=12463&klevu_image=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_target=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_request=click&type=banner&klevu_apiKey=klevu-1234567890',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "customLabel": ""
      },
      {
        "id": "NbLdpQh5907ClqMs5B6Mz",
        "language": "javascript",
        "code": "var formdata = new FormData();\n\nvar requestOptions = {\n  method: 'GET',\n  body: formdata,\n  redirect: 'follow'\n};\n\nfetch('https://stats.ksearchnet.com/analytics/dataTracking?klevu_term=tee&klevu_bannerId=12463&klevu_image=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_target=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_request=click&type=banner&klevu_apiKey=klevu-1234567890', requestOptions)\n  .then(response => response.text())\n  .then(result => console.log(result))\n  .catch(error => console.log('error', error));",
        "customLabel": ""
      },
      {
        "id": "Ss-golxxsBnFs9s0W39ss",
        "language": "nodejs",
        "code": "const axios = require('axios');\nconst FormData = require('form-data');\nlet data = new FormData();\n\nlet config = {\n  method: 'get',\n  maxBodyLength: Infinity,\n  url: 'https://stats.ksearchnet.com/analytics/dataTracking?klevu_term=tee&klevu_bannerId=12463&klevu_image=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_target=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_request=click&type=banner&klevu_apiKey=klevu-1234567890',\n  headers: { \n    ...data.getHeaders()\n  },\n  data : data\n};\n\naxios.request(config)\n.then((response) => {\n  console.log(JSON.stringify(response.data));\n})\n.catch((error) => {\n  console.log(error);\n});\n",
        "customLabel": ""
      },
      {
        "id": "On1k3eW-fooveKEyUj9zw",
        "language": "java",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"text/plain\");\nMediaType JSON = MediaType.parse(\"application/json; charset=utf-8\");\nRequestBody body = RequestBody.create(JSON, \"{}\");\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/dataTracking?klevu_term=tee&klevu_bannerId=12463&klevu_image=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_target=http%3A%2F%2Fmagento243eep1new.com%2Fmedia%2Fcatalog%2Fproduct%2Fcache%2F860616d0cbe1eba675de08cae449bd25%2Fm%2Fj%2Fmj08-gray_main_1.jpg&klevu_request=click&type=banner&klevu_apiKey=klevu-1234567890\")\n  .method(\"GET\", body)\n  .build();\nResponse response = client.newCall(request).execute();",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "On1k3eW-fooveKEyUj9zw"
  },
  "results": {
    "languages": [
      {
        "id": "EBSiH3ekWmQpZne3ITOcF",
        "language": "200",
        "customLabel": "",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>"
      }
    ],
    "selectedLanguageId": "EBSiH3ekWmQpZne3ITOcF"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "name": "klevu_term",
        "kind": "required",
        "type": "string",
        "description": "This field refers to the search term used when submitting banner click events. When submitting click events on Category pages, you can indicate that it is a banner click event by using an asterisk (*) in place of the actual search term. This helps differentiate it from regular search term submissions.",
        "children": []
      },
      {
        "name": "klevu_bannerId",
        "kind": "required",
        "type": "Number",
        "description": "This will be bannerRef value as shown in above API call response.",
        "children": []
      },
      {
        "name": "klevu_image",
        "kind": "required",
        "type": "string",
        "description": "This is the banner image URL.",
        "children": []
      },
      {
        "name": "klevu_target",
        "kind": "required",
        "type": "string",
        "description": "This is target URL.",
        "children": []
      },
      {
        "name": "klevu_request",
        "kind": "required",
        "type": "string",
        "description": "The value of this field will be “click“.",
        "children": []
      },
      {
        "name": "type",
        "kind": "required",
        "type": "string",
        "description": "The value of this field will be “banner“.",
        "children": []
      },
      {
        "name": "klevu_apiKey",
        "kind": "required",
        "type": "string",
        "description": "This is your Klevu JS API Key.",
        "children": []
      },
      {
        "name": "klevu_bannerName",
        "kind": "optional",
        "type": "string",
        "description": "This is banner name.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-banner-click-events",
  "legacyHash": "qiLJAfwsq2_FXEZssIYIW"
}
```
:::


[title] V1 (deprecated)
[path] Guide/Smart Search/

:::hint{type="warning"}
The v1 APIs are now deprecated! If you are building a new implementation, we strongly recommend using API version 2 by going through V2 [Overview](docId\:cZeodl0sKcuv-18IPupLr)&#x20;
:::

Depending on what details you want Klevu Search servers to return in response, you can use one of the following API methods to search in your index.

- For the “search as you type” sort of interface where you need query suggestions, matching categories, CMS pages and product suggestions, please use the “Search As You Type” method.
- For the search results landing page, if you only need a list of IDs of records relevant to your query, use the ID Search method.
- In addition to record IDs, if you want Klevu Search to return other details such as name, description, price, etc., use the Record Search method.

Both the ID Search and the Record Search methods have parameters that allow you to fetch filters/facets as well.

## Search As You Type

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<cloudSearchURL>/cloud-search/n-search/search",
  "name": "Search as you type",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "ticket",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "term",
        "type": "string",
        "description": "The actual term or a phrase searched by the shopper."
      },
      {
        "kind": "required",
        "name": "sv",
        "type": "string",
        "description": "The sv parameter is used for indicating which version of the Klevu Magento plugin you are using (e.g. 1.2.5). In case of a non-magento store, please use the constant value 20.0.0."
      },
      {
        "kind": "optional",
        "name": "autoComplete",
        "type": "Boolean",
        "description": "If true, the autosuggestions matching the submitted query terms are returned. \nDefault value is false. \t"
      },
      {
        "kind": "optional",
        "name": "typeOfSuggestions",
        "type": "string",
        "description": "Used for specifying the kind of non-product suggestions (e.g. cms, category etc.) needed to be fetched. Use \":\" as a separator. Possible values: cms, category"
      },
      {
        "kind": "optional",
        "name": "noOfResults",
        "type": "Integer",
        "description": "Indicates the number of records to be fetched for each type of suggestions. For example, if set to 3, then 3 products, 3 categories and 3 cms pages will be returned."
      },
      {
        "kind": "optional",
        "name": "noOfResultsAC",
        "type": "Integer",
        "description": "Number of autocomplete suggestions to return."
      },
      {
        "kind": "optional",
        "name": "enablePartialSearch",
        "type": "Boolean",
        "description": "If true, the partial search is enabled. For example, searching for let may fetch both letter as well as tablet."
      },
      {
        "kind": "optional",
        "name": "sortOrder",
        "type": "string",
        "description": "If you want to sort results in certain order. please use one of the following values:\n- rel for Relevance,\n- lth for Price: Low to High,\n- htl for Price: High to Low."
      },
      {
        "kind": "optional",
        "name": "showOutOfStockProducts",
        "type": "Boolean",
        "description": "True to include out of stock products in the search result set, false otherwise. "
      },
      {
        "kind": "optional",
        "name": "priceFieldSuffix",
        "type": "string",
        "description": "If you are a shopify plus customer with the multicurrency feature enabled, you can now provide a currency (other than the base currency of your store), to fetch prices in that currency. If in case the prices are not available in the supplied currency, Klevu will return prices in the base currency of the store. e.g. priceFieldSuffix=USD"
      },
      {
        "kind": "optional",
        "name": "visibility",
        "type": "string",
        "description": "Always set this parameter to search to include products with the visibility of search to be included in the result set."
      },
      {
        "kind": "optional",
        "name": "resultForZero",
        "type": "Number",
        "description": "In case the original query does not produce any result, setting this parameter to value 1, will bring products that are most popular on the site or are popular in the recentCategory as below."
      },
      {
        "kind": "optional",
        "name": "recentCategory",
        "type": "string",
        "description": "Name of a category whose product was clicked most recently. this parameter is used in conjuction with resultForZero parameter to produce suggestions in case no result is found for the query."
      },
      {
        "kind": "optional",
        "name": "noOfResultsZero",
        "type": "Integer",
        "description": "If the fallback results are enabled for when there is no result found for a query, this parameter tells how many results should be retrieved."
      },
      {
        "kind": "optional",
        "name": "optionalFilters",
        "type": "string",
        "description": "A parameter to enable personalisation. It instructs Klevu to boost products with the filter values specified here. In case of multiple filters, please use the double semicolon (;;) as a delimiter\n\nWith each filter value, one can assign a boost score.\n\nFor example, if in past a user was seen preferring green color products over any other color and brand to be nike, one can specify the optionalFilters as the following:\n\ne.g. color:green^10;;brand:nike^3.0\n\nHere, use ;; as a delimiter between two filter values and a score between 1 and 100 to boost filter options.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters."
      },
      {
        "kind": "optional",
        "name": "responseType",
        "type": "string",
        "description": "Type of response to be returned. Possible values are xml or json"
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "{\n    \"meta\": {\n        \"layoutId\": \"\",\n        \"layoutType\": \"\",\n        \"noOfResults\": 2,\n        \"paginationStartFrom\": 0,\n        \"powerdByLogo\": \"\",\n        \"totalResultsFound\": 404,\n        \"typeOfQuery\": \"WILDCARD_AND\",\n        \"storeBaseCurrency\": \"GBP\",\n        \"notificationCode\": 1,\n        \"term\": \"r\",\n        \"excludeIds\": null,\n        \"isPersonalised\": false,\n        \"idsUsedForPersonalisation\": null\n    },\n    \"result\": [\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Fitness Equipment\",\n            \"itemGroupId\": \"4384059883582\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"19.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ug05-gr-0_e8c85261-d103-4b09-9460-d8e0a2db97f5_medium.jpg?v=1575478397\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366497206334\",\n            \"imageHover\": \"\",\n            \"sku\": \"24-UG05\",\n            \"brand\": \"KSD\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/ug05-gr-0_e8c85261-d103-4b09-9460-d8e0a2db97f5_medium.jpg?v=1575478397\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"19.0\",\n            \"oldPrice\": \"19.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Accessories;;Fitness Equipment  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/go-getr-pushup-grips\",\n            \"tags\": \"Durable, Grips, pushup\",\n            \"name\": \"Go-Get'r Pushup Grips\",\n            \"shortDesc\": \"The Go-Get'r Pushup Grips safely provide the extra range of motion you need for a deep-dip routine targeting core, shoulder, chest and arm strength. Do fewer pushups using more energy, getting better results faster than the standard floor-level te\",\n            \"category\": \"Accessories;;Fitness Equipment\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        },\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Jackets\",\n            \"itemGroupId\": \"4384032915518\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"60.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj05-red_main_f6c5dcb4-59e1-42cd-aeb6-3faf067c4935_medium.jpg?v=1575477999\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366455066686\",\n            \"imageHover\": \"\",\n            \"sku\": \"WJ05-XS-Red\",\n            \"brand\": \"KKE\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/wj05-red_main_f6c5dcb4-59e1-42cd-aeb6-3faf067c4935_medium.jpg?v=1575477999\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"60.0\",\n            \"oldPrice\": \"60.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Jackets  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/riona-full-zip-jacket-red\",\n            \"tags\": \"comfort, machine, royal, running, zipped\",\n            \"size\": \"Medium\",\n            \"name\": \"Riona Full Zip Jacket\",\n            \"shortDesc\": \"The Riona Basic Zip Jacket makes the perfect extra layer for cold-weather workouts. It features amazing breathability and moisture management, but full-length zipper lets you moderate your core temperature even more. • Brown heather full zi\",\n            \"category\": \"Jackets\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        }\n    ],\n    \"filters\": [],\n    \"price\": {\n        \"min\": \"\",\n        \"max\": \"\",\n        \"start\": \"\",\n        \"end\": \"\"\n    },\n    \"autoComplete\": [],\n    \"popularTerm\": [],\n    \"pages\": [\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"pages\",\n            \"itemGroupId\": \"page_50756288574\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"EUR\",\n            \"price\": \"0.0\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"\",\n            \"currency\": \"EUR\",\n            \"inStock\": \"yes\",\n            \"id\": \"page_50756288574\",\n            \"imageHover\": \"\",\n            \"startPrice\": \"\",\n            \"image\": \"\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"0.0\",\n            \"oldPrice\": \"0.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_CMS  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/pages/recipe-fish-chips\",\n            \"name\": \"Recipe: Fish & Chips\",\n            \"shortDesc\": \"Just a test recipe for Fish & Chips.\",\n            \"typeOfRecord\": \"KLEVU_CMS\"\n        },\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"pages\",\n            \"itemGroupId\": \"page_53478424638\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"EUR\",\n            \"price\": \"0.0\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"\",\n            \"currency\": \"EUR\",\n            \"inStock\": \"yes\",\n            \"id\": \"page_53478424638\",\n            \"imageHover\": \"\",\n            \"startPrice\": \"\",\n            \"image\": \"\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"0.0\",\n            \"oldPrice\": \"0.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_CMS  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/pages/search-results\",\n            \"name\": \"Search Results\",\n            \"shortDesc\": \"\",\n            \"typeOfRecord\": \"KLEVU_CMS\"\n        }\n    ],\n    \"categories\": [],\n    \"popularProducts\": [],\n    \"recentlyViewedProducts\": [],\n    \"ranges\": [],\n    \"error\": {\n        \"errorMessage\": \"\"\n    }\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "ewnRZCOKsK8s4PdjFvhyM",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15.ksearchnet.com/cloud-search/n-search/search?ticket=klevu-156925593843210765&term=r&sv=20.0.0&autoComplete=false&autoCompleteFilters=category:cms&noOfResults=2&showOutOfStockProducts=false&responseType=json',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "ewnRZCOKsK8s4PdjFvhyM"
  },
  "description": "Use this API endpoint to build a search as you type solution. It produces query suggestions, category suggestions, CMS page suggestions and products matching the customer query.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "search-as-you-type-1",
  "legacyHash": "69i_-L-XlhGvweGovwvrH"
}
```
:::

## Record Search

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<cloudSearchURL>/cloud-search/n-search/search",
  "name": "Record search",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "ticket",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "term",
        "type": "string",
        "description": "The actual term or a phrase searched by the shopper."
      },
      {
        "kind": "required",
        "name": "sv",
        "type": "string",
        "description": "The sv parameter is used for indicating which version of the Klevu Magento plugin you are using (e.g. 1.2.5). In case of a non-magento store, please use the constant 20.0.0"
      },
      {
        "kind": "optional",
        "name": "paginationStartsFrom",
        "type": "Integer",
        "description": "Index of the first record to be fetched. If for example showing 12 results per page, use the index 12 for the second page and 24 for the third page and so on.  Default value is 0."
      },
      {
        "kind": "optional",
        "name": "noOfResults",
        "type": "Number",
        "description": "Indicates the number of records to be fetched. If for example, paginationStartsFrom is set to 0, it will obtain results from 0. Default value is 12. "
      },
      {
        "kind": "optional",
        "name": "enablePartialSearch",
        "type": "Boolean",
        "description": "If true, the partial search is enabled. For example, searching for let may fetch letter as well as tablet. Default value is false. "
      },
      {
        "kind": "optional",
        "name": "category",
        "type": "string",
        "description": "To filter results by specific category.\n\nTo fetch only products use KLEVU_PRODUCT as a value.\nTo fetch only Category pages, use KLEVU_CATEGORY as a value.\nTo fetch only CMS pages, use KLEVU_CMS as a value.\n\nUse ~.~ as a delimiter when supplying more than one values.\n\ne.g. KLEVU_PRODUCT~.~electronics~.~furniture\n\nThis will search for “products” where the category is either electronics or furniture."
      },
      {
        "kind": "optional",
        "name": "enableFilters",
        "type": "Boolean",
        "description": "If set to true, filters relevant to the search results are retrieved and included in the response. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "enableMultiSelectFilters",
        "type": "Boolean",
        "description": "If set to true, we treat different values of a filter as checkboxes. Otherwise, if set to false, they are treated as radio buttons.\n\ne.g. color:green;;color:white;;brand:nike\nWhen set to true, it finds products with either green OR white color with the brand nike. When set to false, it finds products with both green AND white color AND brand nike. Default value is false. "
      },
      {
        "kind": "optional",
        "name": "applyFilters",
        "type": "string",
        "description": "Tells Klevu which filters to apply on the search results. In case of multiple filters, please use the double semicolon (;;) as the delimiter.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters.\n\ne.g. color:green;;color:white;;brand:nike"
      },
      {
        "kind": "optional",
        "name": "maxNoOfValuesInAFilter",
        "type": "Integer",
        "description": "Number of values to return for each filter. The default is 50. "
      },
      {
        "kind": "optional",
        "name": "sortOrder",
        "type": "string",
        "description": "If you want to sort results in certain order, please use one of the following values:\n- rel for Relevance,\n- lth for Price: Low to High,\n- htl for Price: High to Low. \nThe default value is rel. "
      },
      {
        "kind": "optional",
        "name": "showOutOfStockProducts",
        "type": "Boolean",
        "description": "True to include out of stock products in the search result set, false otherwise. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "fetchMinMaxPrice",
        "type": "Boolean",
        "description": "If set to true, it returns the minimum and maximum prices found for the obtained search results. This can be used, for example, for displaying price slider. If set to false, Klevu will return price ranges (e.g. 0-500, 500-1000 etc.). The price range intervals are dynamically generated by Klevu. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "priceFieldSuffix",
        "type": "string",
        "description": "If you are a shopify plus customer with the multicurrency feature enabled, you can now provide a currency (other than the base currency of your store), to fetch prices in that currency. If in case the prices are not available in the supplied currency, Klevu will return prices in the base currency of the store. e.g. priceFieldSuffix=USD"
      },
      {
        "kind": "optional",
        "name": "visibility",
        "type": "string",
        "description": "Always set this parameter to search to include products with the visibility of search to be included in the result set. The default value is search. "
      },
      {
        "kind": "optional",
        "name": "resultForZero",
        "type": "Integer",
        "description": "In case the original query does not produce any result, setting this parameter to value 1, will bring products that are most popular on the site or are popular in the recentCategory as below. The default value is 0. "
      },
      {
        "kind": "optional",
        "name": "recentCategory",
        "type": "string",
        "description": "Name of a category whose product was clicked most recently. this parameter is used in conjuction with resultForZero parameter to produce suggestions in case no result is found for the query."
      },
      {
        "kind": "optional",
        "name": "noOfResultsZero",
        "type": "Integer",
        "description": "If the fallback results are enabled for when there is no result found for a query, this parameter tells how many results should be retrieved. The default value is 5."
      },
      {
        "kind": "optional",
        "name": "optionalFilters",
        "type": "string",
        "description": "A parameter to enable personalisation. It instructs Klevu to boost products with the filter values specified here. In case of multiple filters, please use the double semicolon (;;) as a delimiter\n\nWith each filter value, one can assign a boost score.\n\nFor example, if in past a user was seen preferring green color products over any other color and brand to be nike, one can specify the optionalFilters as the following:\n\ne.g. color:green^10;;brand:nike^3.0\n\nHere, use ;; as a delimiter between two filter values and a score between 1 and 100 to boost filter options.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters."
      },
      {
        "kind": "optional",
        "name": "responseType",
        "type": "string",
        "description": "Type of response to be returned. Possible values are xml or json. The default value is xml. "
      },
      {
        "kind": "optional",
        "name": "lsqt",
        "type": "string",
        "description": "When you receive a response for a search query, look at the value of the typeOfQuery element under the metaData section. When you fire a subsequent query (e.g. to apply additional filters, or to obtain results for the next page), pass this value as the value of the lsqt (last search query type) parameter.  Possible values are WILDCARD_AND, FUZZY_AND, OR, FUZZY_OR. "
      },
      {
        "kind": "optional",
        "name": "fl",
        "type": "string",
        "description": "When Klevu returns search results, the response has certain fields for each record included. If you like to retrieve only a set of selected filters, use a list of comma separated field names."
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "{\n    \"meta\": {\n        \"layoutId\": \"\",\n        \"layoutType\": \"\",\n        \"noOfResults\": 2,\n        \"paginationStartFrom\": 0,\n        \"powerdByLogo\": \"\",\n        \"totalResultsFound\": 448,\n        \"typeOfQuery\": \"WILDCARD_AND\",\n        \"storeBaseCurrency\": \"GBP\",\n        \"notificationCode\": 1,\n        \"term\": \"a\",\n        \"excludeIds\": null,\n        \"isPersonalised\": false,\n        \"idsUsedForPersonalisation\": null\n    },\n    \"result\": [\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Watches\",klevu\n            \"itemGroupId\": \"4384059326526\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"45.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg04-bk-0_b0a2adf9-f0c0-4814-8aa7-e421120afb06_medium.jpg?v=1575478388\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366496616510\",\n            \"imageHover\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg04-bk-0_1024x1024_1_cb15759f-9c8c-4899-a68a-e379c5fe3735_medium.jpg?v=1575478388\",\n            \"sku\": \"24-MG04\",\n            \"brand\": \"KSD\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg04-bk-0_b0a2adf9-f0c0-4814-8aa7-e421120afb06_medium.jpg?v=1575478388\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"45.0\",\n            \"oldPrice\": \"45.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Watches  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/aim-analog-watch\",\n            \"tags\": \"analog, strap fit, watch\",\n            \"size\": \"Free Size\",\n            \"name\": \"Aim Analog Watch\",\n            \"shortDesc\": \"Stay light-years ahead of the competition with our Aim Analog Watch. The flexible, rubberized strap is contoured to conform to the shape of your wrist for a comfortable all-day fit. The face features three illuminated hands, a digital read-out of\",\n            \"category\": \"Watches\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        },\n        {\n            \"discount\": \"\",\n            \"hideGroupPrices\": \"\",\n            \"type\": \"Watches\",\n            \"itemGroupId\": \"4384058933310\",\n            \"freeShipping\": \"\",\n            \"storeBaseCurrency\": \"GBP\",\n            \"price\": \"55.00\",\n            \"toPrice\": \"\",\n            \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg05-br-0_5300c0c5-9008-480a-ab61-cd7a670d18e0_medium.jpg?v=1575478382\",\n            \"currency\": \"GBP\",\n            \"inStock\": \"yes\",\n            \"id\": \"31366496124990\",\n            \"imageHover\": \"\",\n            \"sku\": \"24-MG05\",\n            \"brand\": \"KSD\",\n            \"startPrice\": \"\",\n            \"image\": \"https://cdn.shopify.com/s/files/1/0116/9457/1582/products/mg05-br-0_5300c0c5-9008-480a-ab61-cd7a670d18e0_medium.jpg?v=1575478382\",\n            \"deliveryInfo\": \"\",\n            \"hideAddToCart\": \"\",\n            \"salePrice\": \"55.0\",\n            \"oldPrice\": \"55.0\",\n            \"swatches\": {\n                \"swatch\": [],\n                \"lowestPrice\": \"\",\n                \"numberOfAdditionalVariants\": \"\"\n            },\n            \"weight\": \"\",\n            \"klevu_category\": \"KLEVU_PRODUCT;Products;;Watches  @ku@kuCategory@ku@\",\n            \"totalVariants\": \"0\",\n            \"groupPrices\": \"\",\n            \"url\": \"https://jsv2-shopify-demo.ksearchmisc.com/products/cruise-dual-analog-watch\",\n            \"tags\": \"analog, cruise, leather band, watch\",\n            \"size\": \"Free Size\",\n            \"name\": \"Cruise Dual Analog Watch\",\n            \"shortDesc\": \"Whether you're traveling or wish you were, you'll never let time zones perplex you again with the Cruise Dual Analog Watch. The thick, adjustable band promises a comfortable, personalized fit to this classy, modern time piece. Two dia\",\n            \"category\": \"Watches\",\n            \"typeOfRecord\": \"KLEVU_PRODUCT\"\n        }\n    ],\n    \"filters\": [],\n    \"price\": {\n        \"min\": \"\",\n        \"max\": \"\",\n        \"start\": \"\",\n        \"end\": \"\"\n    },\n    \"autoComplete\": [],\n    \"popularTerm\": [],\n    \"pages\": [],\n    \"categories\": [],\n    \"popularProducts\": [],\n    \"recentlyViewedProducts\": [],\n    \"ranges\": [],\n    \"error\": {\n        \"errorMessage\": \"\"\n    }\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "uQ140yeowlCssb8Z1TFzR",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15.ksearchnet.com/cloud-search/n-search/search?ticket=klevu-156925593843210765&term=a&sv=20.0.0&paginationStartsFrom=0&noOfResults=2&enablePartialSearch=false&category=KLEVU_PRODUCT&enableFilters=false&enableMultiSelectFilters=false&showOutOfStockProducts=true&responseType=json',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "uQ140yeowlCssb8Z1TFzR"
  },
  "description": "Use this API method if you want not only the record IDs but also other details associated with the matching records. The method allows you to retrieve facets and autosuggestions as well.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "record-search-1",
  "legacyHash": "EEMY_OqxFW3qUjQkt1twQ"
}
```
:::

## ID search

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<cloudSearchURL>/cloud-search/n-search/idsearch",
  "name": "ID search",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "ticket",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "term",
        "type": "string",
        "description": "The actual term or a phrase searched by the shopper."
      },
      {
        "kind": "required",
        "name": "sv",
        "type": "string",
        "description": "The sv parameter is used for indicating which version of the Klevu Magento plugin you are using (e.g. 1.2.5). In case of a non-magento store, please use the constant 20.0.0"
      },
      {
        "kind": "optional",
        "name": "paginationStartsFrom",
        "type": "Integer",
        "description": "Index of the first record to be fetched. If for example showing 12 results per page, use the index 12 for the second page and 24 for the third page and so on.  Default value is 0."
      },
      {
        "kind": "optional",
        "name": "noOfResults",
        "type": "Number",
        "description": "Indicates the number of records to be fetched. If for example, paginationStartsFrom is set to 0, it will obtain results from 0. Default value is 12. "
      },
      {
        "kind": "optional",
        "name": "enablePartialSearch",
        "type": "Boolean",
        "description": "If true, the partial search is enabled. For example, searching for let may fetch letter as well as tablet. Default value is false. "
      },
      {
        "kind": "optional",
        "name": "category",
        "type": "string",
        "description": "To filter results by specific category.\n\nTo fetch only products use KLEVU_PRODUCT as a value.\nTo fetch only Category pages, use KLEVU_CATEGORY as a value.\nTo fetch only CMS pages, use KLEVU_CMS as a value.\n\nUse ~.~ as a delimiter when supplying more than one values.\n\ne.g. KLEVU_PRODUCT~.~electronics~.~furniture\n\nThis will search for “products” where the category is either electronics or furniture."
      },
      {
        "kind": "optional",
        "name": "enableFilters",
        "type": "Boolean",
        "description": "If set to true, filters relevant to the search results are retrieved and included in the response. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "enableMultiSelectFilters",
        "type": "Boolean",
        "description": "If set to true, we treat different values of a filter as checkboxes. Otherwise, if set to false, they are treated as radio buttons.\n\ne.g. color:green;;color:white;;brand:nike\nWhen set to true, it finds products with either green OR white color with the brand nike. When set to false, it finds products with both green AND white color AND brand nike. Default value is false. "
      },
      {
        "kind": "optional",
        "name": "applyFilters",
        "type": "string",
        "description": "Tells Klevu which filters to apply on the search results. In case of multiple filters, please use the double semicolon (;;) as the delimiter.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters.\n\ne.g. color:green;;color:white;;brand:nike"
      },
      {
        "kind": "optional",
        "name": "maxNoOfValuesInAFilter",
        "type": "Integer",
        "description": "Number of values to return for each filter. The default is 50. "
      },
      {
        "kind": "optional",
        "name": "sortOrder",
        "type": "string",
        "description": "If you want to sort results in certain order, please use one of the following values:\n- rel for Relevance,\n- lth for Price: Low to High,\n- htl for Price: High to Low. \nThe default value is rel. "
      },
      {
        "kind": "optional",
        "name": "showOutOfStockProducts",
        "type": "Boolean",
        "description": "True to include out of stock products in the search result set, false otherwise. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "fetchMinMaxPrice",
        "type": "Boolean",
        "description": "If set to true, it returns the minimum and maximum prices found for the obtained search results. This can be used, for example, for displaying price slider. If set to false, Klevu will return price ranges (e.g. 0-500, 500-1000 etc.). The price range intervals are dynamically generated by Klevu. The default value is false. "
      },
      {
        "kind": "optional",
        "name": "priceFieldSuffix",
        "type": "string",
        "description": "If you are a shopify plus customer with the multicurrency feature enabled, you can now provide a currency (other than the base currency of your store), to fetch prices in that currency. If in case the prices are not available in the supplied currency, Klevu will return prices in the base currency of the store. e.g. priceFieldSuffix=USD"
      },
      {
        "kind": "optional",
        "name": "visibility",
        "type": "string",
        "description": "Always set this parameter to search to include products with the visibility of search to be included in the result set. The default value is search. "
      },
      {
        "kind": "optional",
        "name": "resultForZero",
        "type": "Integer",
        "description": "In case the original query does not produce any result, setting this parameter to value 1, will bring products that are most popular on the site or are popular in the recentCategory as below. The default value is 0. "
      },
      {
        "kind": "optional",
        "name": "recentCategory",
        "type": "string",
        "description": "Name of a category whose product was clicked most recently. this parameter is used in conjuction with resultForZero parameter to produce suggestions in case no result is found for the query."
      },
      {
        "kind": "optional",
        "name": "noOfResultsZero",
        "type": "Integer",
        "description": "If the fallback results are enabled for when there is no result found for a query, this parameter tells how many results should be retrieved. The default value is 5."
      },
      {
        "kind": "optional",
        "name": "optionalFilters",
        "type": "string",
        "description": "A parameter to enable personalisation. It instructs Klevu to boost products with the filter values specified here. In case of multiple filters, please use the double semicolon (;;) as a delimiter\n\nWith each filter value, one can assign a boost score.\n\nFor example, if in past a user was seen preferring green color products over any other color and brand to be nike, one can specify the optionalFilters as the following:\n\ne.g. color:green^10;;brand:nike^3.0\n\nHere, use ;; as a delimiter between two filter values and a score between 1 and 100 to boost filter options.\n\nValues provided here should be the strings taken from the value attribute of the option element under the filters."
      },
      {
        "kind": "optional",
        "name": "responseType",
        "type": "string",
        "description": "Type of response to be returned. Possible values are xml or json. The default value is xml. "
      },
      {
        "kind": "optional",
        "name": "lsqt",
        "type": "string",
        "description": "When you receive a response for a search query, look at the value of the typeOfQuery element under the metaData section. When you fire a subsequent query (e.g. to apply additional filters, or to obtain results for the next page), pass this value as the value of the lsqt (last search query type) parameter.  Possible values are WILDCARD_AND, FUZZY_AND, OR, FUZZY_OR. "
      },
      {
        "kind": "optional",
        "name": "fl",
        "type": "string",
        "description": "When Klevu returns search results, the response has certain fields for each record included. If you like to retrieve only a set of selected filters, use a list of comma separated field names."
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "{\n    \"meta\": {\n        \"layoutId\": \"\",\n        \"layoutType\": \"\",\n        \"noOfResults\": 2,\n        \"paginationStartFrom\": 0,\n        \"powerdByLogo\": \"\",\n        \"totalResultsFound\": 398,\n        \"typeOfQuery\": \"WILDCARD_AND\",\n        \"storeBaseCurrency\": \"\",\n        \"notificationCode\": 1,\n        \"term\": \"r\",\n        \"excludeIds\": null,\n        \"isPersonalised\": false,\n        \"idsUsedForPersonalisation\": null\n    },\n    \"result\": [\n        {\n            \"id\": \"31366497206334\",\n            \"itemGroupId\": \"4384059883582\"\n        },\n        {\n            \"id\": \"31366455066686\",\n            \"itemGroupId\": \"4384032915518\"\n        }\n    ],\n    \"filters\": [],\n    \"price\": {\n        \"min\": \"\",\n        \"max\": \"\",\n        \"start\": \"\",\n        \"end\": \"\"\n    },\n    \"autoComplete\": [],\n    \"popularTerm\": [],\n    \"pages\": [],\n    \"categories\": [],\n    \"popularProducts\": [],\n    \"recentlyViewedProducts\": [],\n    \"ranges\": [],\n    \"error\": {\n        \"errorMessage\": \"\"\n    }\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "uQ140yeowlCssb8Z1TFzR",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs15.ksearchnet.com/cloud-search/n-search/idsearch?ticket=klevu-156925593843210765&term=r&sv=20.0.0&paginationStartsFrom=0&noOfResults=2&enablePartialSearch=false&category=KLEVU_PRODUCT&enableFilters=false&enableMultiSelectFilters=false&showOutOfStockProducts=false&responseType=json',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "uQ140yeowlCssb8Z1TFzR"
  },
  "description": "Use this API method if you require only the IDs of the records matching your query. The method also allows you to retrieve facets associated with the search results.",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "id-search-1",
  "legacyHash": "s_PquW4wS29wJg2AJtEiN"
}
```
:::




[title] Klaviyo : Search Events
[path] Guide/Connectors/

The following guide is for integrating Klevu search events into Klaviyos event tracking using API.

:::hint{type="warning"}
To implement the connector to Klaviyo, you need an active subscription to Klaviyo and be on a Klevu plan with Personalization enabled.
:::



For details on the setup and configuration of Klevu to Klaviyo events within the platform(s), please see: [https://help.klevu.com/support/solutions/articles/5000878078-integration-steps-to-send-klevu-search-events-to-klaviyo](https://help.klevu.com/support/solutions/articles/5000878078-integration-steps-to-send-klevu-search-events-to-klaviyo)

:::hint{type="info"}
You must have Klaviyo active on the site to utilize Klaviyo's API for pushing event data.
:::



**There are three key aspects to consider:**

1. Check the data against Klevu NLP Annotations API
2. Prepare the data object for push to Klaviyo
3. Submit object to Klaviyo as a Klevu Search event

# 1. Check the data against Klevu NLP Annotations API

Klevu provides an external function for Klaviyo event tracking that will analyze and prepare the values to be sent to Klaviyo. Although not required, this step is recommended to get the optimal values that will be injected into the Klaviyo event flow.
This check may be fired after a search query and held in localstorage for use in constructing the object for the Klaviyo event push (see step 2 below)

:::ApiMethodV2
```json
{
  "name": "Request the NLP annotations from Klevu",
  "method": "GET",
  "url": "https://nlp-services.ksearchnet.com/<KLEVU_API_KEY>/annotations",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "_sFNtkflJKrbY9f9O85Oy",
        "language": "none",
        "code": "?query={search query}\n            &title={product title}\n            &category={product attribute 'category' from search results}\n            &language={store language ISO code}",
        "customLabel": "Query Parameters"
      }
    ],
    "selectedLanguageId": "_sFNtkflJKrbY9f9O85Oy"
  },
  "results": {
    "languages": [
      {
        "id": "uLmfUMedP1sWYxjQ6dU0a",
        "language": "200",
        "customLabel": "",
        "code": "{\n   \"apiKey\":\"String\",\n   \"annotations\":{\n     \"fullTerm\" : [\"String\"]\n     \"subjects\" : [\"STR\",\"STR\",......],\n   },\n   \"responseMessage\":\"String\",\n   \"qTime\":Long  //query time\n}"
      },
      {
        "id": "CO-N3V0QxSC5N8CfOriKW",
        "language": "404",
        "customLabel": "",
        "code": "{\n      \"message\": \"Ain't no cake like that.\"\n    }"
      }
    ],
    "selectedLanguageId": "uLmfUMedP1sWYxjQ6dU0a"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "name": "query",
        "kind": "optional",
        "type": "string",
        "description": "The search query term as entered by the end-user",
        "children": []
      },
      {
        "name": "title",
        "kind": "optional",
        "type": "string",
        "description": "The name of the product that has been clicked (or otherwise given context)",
        "children": []
      },
      {
        "name": "category",
        "kind": "optional",
        "type": "string",
        "description": "The category of the product that has been clicked (or otherwise given context)",
        "children": []
      },
      {
        "name": "language",
        "kind": "optional",
        "type": "string",
        "description": "The store ISO language code",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "request-the-nlp-annotations-from-klevu",
  "legacyHash": "UffeZ-ds-xmkcLOTqrVfX"
}
```
:::

**Example Response**

```json
{
    "apiKey": "klevu-12345",
    "annotations": {
        "subjects": [
            "sneakers",
            "sneaker"
        ],
        "fullTerm": [
            "men shoes"
        ]
    },
    "responseMessage": "SUCCESS",
    "qtime": 0
}
```

#

# 2. Prepare the data object for push to Klaviyo

The values returned by the Klevu Annotations query will be used in the object sent to Klaviyo for use in the event flow.
**Product Clicked** tracking and **Search Results** data will need to be captured independently for use in the object.

**Build the object to push to Klaviyo using the following JSON format:**

```json
{
   "Search Term": "String", // original search query
   "Search Term(full)": ["String"], //contained in the NLP response object
   "Subjects": ["String","String"], //contained in the NLP response object
   "Total Number of Product Results": Integer, // total number of products found by the search query
   "Product Clicked": {
            // product data for clicked product
    },
    "Search Results":[
              {
             // product data for first product in the klevu search response
              },
              {
              // product data for next product in the klevu search response
               },
               ... // 10 products
    ],
    "Recommended results": [] 
              // optional list of products formated similar to
              // the Search Results, only valid in the case of
              // click being extracted from a fallback query
}
```

**Example:**

```json
{
     "Search Term": "men shoes", 
     "Search Term(full)": ["men shoes"], 
     "Subjects": ["sneakers","sneaker"], 
     "Total Number of Product Results": 2, 
     "Product Clicked": {
      			"name": "Acme Men Black Sneakers",
				"id": "456789",
				"url": "https://myexample.com/products/acme-men-black-sneakers",
				"imageUrl": "https://myexample.com/images/products/456789_images_medium.jpg?v=1666139322",
				"price": "26.95",
				"salePrice": "26.95"
      },
      "Search Results":[
              {
				"name": "Cool Men Khaki Shoes",
				"id": "987654",
				"url": "https://myexample.com/products/cool-men-khaki-shoes",
				"imageUrl": "https://myexample.com/images/products/987654_images_medium.jpg",
				"price": "29.95",
				"salePrice": "29.95"
			  },
			  {
				"name": "Acme Men Black Sneakers",
				"id": "456789",
				"url": "https://myexample.com/products/skechers-men-black-sneakers",
				"imageUrl": "https://myexample.com/images/products/456789_images_medium.jpg",
				"price": "26.95",
				"salePrice": "26.95"
			  }
      ],
}
```

#

# 3. Submit object to Klaviyo as a Klevu Search event

```javascript
_learnq.push(["track", "Klevu Search", <objectToPush>]);
```

:::hint{type="info"}
See Klaviyo developer documentation for details on submitting tracked events.
[https://developers.klaviyo.com/en/v1-2/docs/javascript-api](https://developers.klaviyo.com/en/v1-2/docs/javascript-api)
:::

The event Klevu Search will now be available within the ***Klaviyo Profile > Events*** view

::Image[The event Klevu Search will now be available within the Klaviyo Profile > Events view&#xA;&#xA;]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/24WpWz2Ja3Qqd8ZWiIisz_image.png" size="70" width="622" height="579" position="center" caption="Klaviyo Profile > Events"}


[title] Similar Products
[path] Guide/Smart Recommendations/

:::hint{type="info"}
If you haven't gone through the prerequisites and the v2 structure, please have a look at [Overview](docId\:cZeodl0sKcuv-18IPupLr) &#x20;
:::

Klevu can power a recommendation banner showcasing any products which are similar to the current product. The most common placements for this banner type are:

**Product Page: You May Also Like**
Show a recommendation banner with similar products from the store.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://eucs19v2.ksearchnet.com/cs/v2/search",
  "name": "Similar Products",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "typeOfRequest",
        "type": "String",
        "description": "For this recommendation type, please specify RECS_SIMILAR."
      },
      {
        "kind": "required",
        "name": "recentObjects",
        "type": "Array",
        "description": "The Klevu ID of the product or products you will use for context. Klevu will find other products similar to the ones specified in this field."
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "3XlvmT855lGkJOht0nPXg",
        "code": "{\n    \"meta\": {\n        \"qTime\": 25,\n        \"responseCode\": 200\n    },\n    \"queryResults\": [\n        {\n            \"id\": \"recsSimilar\",\n            \"meta\": {\n                \"qTime\": 15,\n                \"noOfResults\": 12,\n                \"totalResultsFound\": 64,\n                \"typeOfSearch\": \"WILDCARD_AND\",\n                \"offset\": 0,\n                \"debuggingInformation\": {},\n                \"notificationCode\": 1,\n                \"searchedTerm\": \"*\",\n                \"apiKey\": \"klevu-158755634955912036\",\n                \"isPersonalised\": true,\n                \"idsUsedForPersonalisation\": [\n                    \"34322682183811\"\n                ]\n            },\n            \"records\": [\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759836803\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234340_medium.jpg?v=1611184264\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322682511491\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882497-s\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665234340_medium.jpg?v=1611184264\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 1,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-navy-blue-zipper-hooded-fleece-sweatshirt-ox00006\",\n                    \"name\": \"WoMen's Zipper Hooded Fleece Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: Happiness ist. Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192749842563\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322425184387\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882422-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231658_medium.jpg?v=1611183787\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 3,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-printed-hooded-oversize-knitted-sweatshirt\",\n                    \"name\": \"WoMen's Printed Hooded Oversize Knitted Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Yellow Hoodie thin\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192753152131\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"51.42\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=34322463555715,34322464047235,34322464473219,34322464768131,34322465194115,34322465554563,34322465783939\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322465554563\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797422_medium.jpg?v=1611184206&vid=34322466177155,34322466603139,34322466930819,34322467192963,34322467586179,34322467946627,34322468339843\",\n                    \"sku\": \"30504298-yellow-hoodie-thin-asian-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"48.48\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=34322463555715,34322464047235,34322464473219,34322464768131,34322465194115,34322465554563,34322465783939\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"51.42\",\n                    \"swatchesInfo\": \"variantColor1:Black Hoodie thin ;;;; variantColor3:Blue Hoodie thick ;;;; variantColor2:White Hoodie thick ;;;; variantColor5:White Hoodie thin ;;;; variantColor4:Black Hoodie thick ;;;; variantColor6:Yellow Hoodie thin ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797423_medium.jpg?v=1611184258&vid=16847225487491 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797419_medium.jpg?v=1611184206&vid=16847185313923 ;;;; variantId6:34322463555715 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797420_medium.jpg?v=1611184206&vid=16847185510531 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797424_medium.jpg?v=1611184206&vid=16847190851715 ;;;; variantId4:34322456838275 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797418_medium.jpg?v=1611184250&vid=16847223521411 ;;;; variantId5:34322460016771 ;;;; variantId2:34322452512899 ;;;; variantId3:34322453889155 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1664797425_medium.jpg?v=1611184240&vid=16847221883011 ;;;; variantId1:34322448646275 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 51,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-hoodies-men-women-2021-spring-sweatshirt-male-japanese-streetwear-oversized-yellow-anime-hoodie-men-sweatshirts\",\n                    \"size\": \"Asian-L\",\n                    \"name\": \"Singleroad Men's Hoodies Men Women 2021 Sweatshirt Male Japanese Streetwear Oversized Anime Hoodie Men Sweatshirts\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192751579267\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231809_medium.jpg?v=1611183862\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322437177475\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882427-l\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665231809_medium.jpg?v=1611183862\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 2,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-hooded-kangaroo-pocket-sweatshirt\",\n                    \"name\": \"WoMen's Hooded Kangaroo Pocket Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192749908099\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"50.00\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232005_medium.jpg?v=1611184179\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322423316611\",\n                    \"imageHover\": \"\",\n                    \"sku\": \"42882435-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1665232005_medium.jpg?v=1611184179\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"50.0\",\n                    \"swatchesInfo\": \"\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Women Sweatshirts  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 1,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/womens-white-plaids-blocky-polarized-sweatshirt\",\n                    \"name\": \"WoMen's Plaids Blocky Polarized Sweatshirt\",\n                    \"shortDesc\": \";;;; Brand Name: FASHİON ROOM Material: Cotton Origin: CN(Origin)\",\n                    \"category\": \"All;;Women Sweatshirts\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men\",\n                    \"color\": \"Army Green\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192759246979\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"44.98\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057851_medium.jpg?v=1611184011&vid=34322647548035,34322648465539,34322649350275,34322650333315,34322651152515,34322651938947\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322649350275\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057848_medium.jpg?v=1611183969&vid=34322652528771,34322653577347,34322654527619,34322655346819,34322656428163,34322657509507\",\n                    \"sku\": \"26977138-army-green-m\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"closure\": \"[Zipper, Zipper]\",\n                    \"decoration\": \"Pockets\",\n                    \"startPrice\": \"44.98\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057851_medium.jpg?v=1611184011&vid=34322647548035,34322648465539,34322649350275,34322650333315,34322651152515,34322651938947\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"44.98\",\n                    \"swatchesInfo\": \"variantColor1:Army Green ;;;; variantColor3:Blue ;;;; variantColor2:Black ;;;; variantColor4:Khaki ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057849_medium.jpg?v=1611184365&vid=16847232991363 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057848_medium.jpg?v=1611183969&vid=16847194030211 ;;;; variantId4:34322664489091 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057852_medium.jpg?v=1611184372&vid=16847233581187 ;;;; variantId2:34322652528771 ;;;; variantId3:34322658656387 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1404057851_medium.jpg?v=1611184011&vid=16847204057219 ;;;; variantId1:34322647548035 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Coats & Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 23,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/brand-2020-thicken-winter-mens-vest-zipper-coat-warm-sleeveless-jacket-casual-fleece-male-vest-coat-army-green-waistcoat-black\",\n                    \"name\": \"Men's Vest Zipper Coat Warm Sleeveless Jacket\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:zipper,zipper; decoration:decoration:pockets; ;;;; Brand Name: UNION ARMY Origin: CN(Origin) Material: Cotton\",\n                    \"category\": \"All;;Mens Coats & Jackets\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men, Men, Men, Men, Teens, Women, Women\",\n                    \"color\": \"Lightblue(asiansize)\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192755216515\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"51.02\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1433101073_medium.jpg?v=1611184236&vid=34322506416259,34322508447875,34322510577795,34322512609411,34322514641027,34322516705411,34322518474883\",\n                    \"season\": \"[Spring, Summer, Autumn, Winter]\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322506416259\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1433101073_medium.jpg?v=1611184236&vid=34322506416259,34322508447875,34322510577795,34322512609411,34322514641027,34322516705411,34322518474883\",\n                    \"sku\": \"25578230-lightblue-asiansize-m\",\n                    \"closure\": \"Zipper Fly\",\n                    \"decoration\": \"Pockets\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"51.02\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1433101073_medium.jpg?v=1611184236&vid=34322506416259,34322508447875,34322510577795,34322512609411,34322514641027,34322516705411,34322518474883\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"51.02\",\n                    \"swatchesInfo\": \"variantColor1:Black(Asian Size) ;;;; variantColor2:LightBlue(AsianSize) ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1433101073_medium.jpg?v=1611184236&vid=16847187968131 ;;;; variantId2:34322506416259 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1433101072_medium.jpg?v=1611184306&vid=16847230009475 ;;;; variantId1:34322495537283 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 9,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/privathinker-men-streetwear-blue-jeans-2020-women-black-jeans-korean-fashions-harem-pants-male-denim-pants-oversize\",\n                    \"size\": \"M, L, Xl, 2xl, 3xl\",\n                    \"fabric\": \"Stripe\",\n                    \"name\": \"Privathinker Men Streetwear Jeans Women Jeans Korean Fashions Harem Pants Male Denim Pants Oversize\",\n                    \"shortDesc\": \"gender:gender:men,man,men,male,teens,women,female; size:size:M,L,XL,2XL,3XL; fabric:fabric:stripe; season:season:spring,summer,autumn,winter; closure:closure:zipper fly; decoration:decoration:pockets; ;;;; Brand Name:\",\n                    \"category\": \"All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men\",\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192754167939\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"48.80\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564139_medium.jpg?v=1611183933&vid=34322491867267,34322492620931,34322493341827,34322494095491,34322495078531,34322495930499,34322505236611\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322493341827\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564140_medium.jpg?v=1611183895&vid=34322504319107,34322507071619,34322508021891,34322509168771,34322510381187,34322511822979,34322513297539\",\n                    \"sku\": \"19131037-black-l\",\n                    \"closure\": \"Zipper\",\n                    \"decoration\": \"Button\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"44.72\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564139_medium.jpg?v=1611183933&vid=34322491867267,34322492620931,34322493341827,34322494095491,34322495078531,34322495930499,34322505236611\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"48.8\",\n                    \"swatchesInfo\": \"variantColor1:Green ;;;; variantColor3:Khaki ;;;; variantColor2:Black ;;;; variantColor5:Black ;;;; variantColor4:Blue ;;;; variantSwatchImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantColor6:Green ;;;; variantSwatchImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/t/2/assets/black.jpg?v=1587554091 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564141_medium.jpg?v=1611183908&vid=16847183642755 ;;;; variantId6:34322506154115 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564142_medium.jpg?v=1611184305&vid=16847229943939 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564139_medium.jpg?v=1611183933&vid=16847188557955 ;;;; variantId4:34322504319107 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564139_medium.jpg?v=1611183933&vid=16847188557955 ;;;; variantId5:34322505236611 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564140_medium.jpg?v=1611183895&vid=16847181316227 ;;;; variantId2:34322491867267 ;;;; variantId3:34322497175683 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1412564141_medium.jpg?v=1611183908&vid=16847183642755 ;;;; variantId1:34322488328323 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All;;Mens Coats & Jackets  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 27,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/jacket-men-2020-new-mens-thick-warm-winter-down-coat-long-fur-collar-army-green-men-parka-fleece-cotton-coat-jacket-parka-men\",\n                    \"size\": \"S, M, L, Xl, 2xl, 3xl, 4xl\",\n                    \"name\": \"Jacket Men New Men's Thick Warm Down Coat Long Fur Collar Army Men Parka Fleece Cotton Coat Jacket Parka Men\",\n                    \"shortDesc\": \"gender:gender:men; size:size:S,M,L,XL,2XL,3XL,4XL]]>; closure:closure:zipper; decoration:decoration:button; ;;;; Brand Name: Asstseries Origin: CN(Origin) Clo\",\n                    \"category\": \"All;;Mens Coats & Jackets\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Pink Sweatshirt Men\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192757510275\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904838631555\",\n                    \"price\": \"47.56\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961918_medium.jpg?v=1611184219&vid=34322615566467,34322616057987,34322616582275,34322617106563,34322617499779,34322617892995\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322616582275\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961918_medium.jpg?v=1611184219&vid=34322615566467,34322616057987,34322616582275,34322617106563,34322617499779,34322617892995\",\n                    \"sku\": \"40668452-pink-sweatshirt-men-asian-xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"44.48\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961918_medium.jpg?v=1611184219&vid=34322615566467,34322616057987,34322616582275,34322617106563,34322617499779,34322617892995\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"47.56\",\n                    \"swatchesInfo\": \"variantColor1:White Sweatshirt Men ;;;; variantColor3:Pink Sweatshirt Men ;;;; variantColor2:Black Sweatshirt Men ;;;; variantColor5:Black Sweatshirt Men ;;;; variantColor4:Khaki Sweatshirt Men ;;;; variantColor6:Khaki Sweatshirt Men ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961917_medium.jpg?v=1611184373&vid=16847233646723 ;;;; variantId6:34322620285059 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961918_medium.jpg?v=1611184219&vid=16847193735299 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961915_medium.jpg?v=1611184301&vid=16847229714563 ;;;; variantId4:34322618253443 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961915_medium.jpg?v=1611184301&vid=16847229714563 ;;;; variantId5:34322618843267 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961917_medium.jpg?v=1611184373&vid=16847233646723 ;;;; variantId2:34322614616195 ;;;; variantId3:34322615566467 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1556961916_medium.jpg?v=1611184219&vid=16847198388355 ;;;; variantId1:34322612682883 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 23,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-crewneck-sweatshirt-men-2020-graffiti-oversized-japanese-streetwear-hip-hop-black-hoodie-men-sweatshirts-hoodies\",\n                    \"size\": \"Asian-XL\",\n                    \"name\": \"Men's Crewneck Sweatshirt Hip Hop Hoodie Sweatshirts\",\n                    \"shortDesc\": \"gender:gender:men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full Gender:\",\n                    \"category\": \"All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"gender\": \"Men, Men\",\n                    \"color\": \"Blue\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192755609731\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"54.58\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707958_medium.jpg?v=1611184280&vid=34322532663427,34322533810307,34322534891651,34322535809155,34322536759427,34322537873539\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322536759427\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707952_medium.jpg?v=1611183966&vid=34322503008387,34322504188035,34322505400451,34322506612867,34322507890819,34322509430915\",\n                    \"sku\": \"12602463-blue-thin-xxl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"closure\": \"Zipper\",\n                    \"decoration\": \"Pattern\",\n                    \"startPrice\": \"54.58\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707958_medium.jpg?v=1611184280&vid=34322532663427,34322533810307,34322534891651,34322535809155,34322536759427,34322537873539\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"54.58\",\n                    \"swatchesInfo\": \"variantColor1:khaki thick ;;;; variantColor3:blue thick ;;;; variantColor2:army thick ;;;; variantColor5:blue thin ;;;; variantColor4:khaki thin ;;;; variantColor6:army thin ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707956_medium.jpg?v=1611184262&vid=16847226372227 ;;;; variantId6:34322538692739 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707954_medium.jpg?v=1611184267&vid=16847227224195 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707953_medium.jpg?v=1611184316&vid=16847230468227 ;;;; variantId4:34322526437507 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707958_medium.jpg?v=1611184280&vid=16847228567683 ;;;; variantId5:34322532663427 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707957_medium.jpg?v=1611184263&vid=16847226536067 ;;;; variantId2:34322510971011 ;;;; variantId3:34322519654531 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-525707952_medium.jpg?v=1611183966&vid=16847195570307 ;;;; variantId1:34322503008387 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 17,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/bomber-jacket-ma1-air-force-pilot-casual-new-arrival-military-style-men-thick-fleece-velvet-coat-winter-male-green-blue-khaki\",\n                    \"name\": \"Bomber Jacket Ma1 Air Force Pilot Casual New Arrival Military Style Men Thick Fleece Coat Male Khaki\",\n                    \"shortDesc\": \"gender:gender:men,men; closure:closure:zipper; decoration:decoration:pattern; ;;;; Brand Name: UNION ARMY Origin: CN(Origin) Closure Type: zipper\",\n                    \"category\": \"All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Black\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192756134019\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"price\": \"48.24\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1124428249_medium.jpg?v=1611184372&vid=34322518048899,34322519359619,34322520375427,34322521587843,34322522800259,34322524078211,34322525356163,34322526273667,34322527289475,34322528108675,34322528927875,34322529714307\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322526273667\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275898_medium.jpg?v=1611184209&vid=34322530631811,34322531516547,34322532466819,34322533286019,34322534072451,34322535088259,34322535907459,34322536857731,34322540429443,34322541248643,34322542198915,34322543181955\",\n                    \"sku\": \"29459443-black-f202-35\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"closure\": \"Zipper Fly\",\n                    \"decoration\": \"Button\",\n                    \"startPrice\": \"37.1\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1124428249_medium.jpg?v=1611184372&vid=34322518048899,34322519359619,34322520375427,34322521587843,34322522800259,34322524078211,34322525356163,34322526273667,34322527289475,34322528108675,34322528927875,34322529714307\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"48.24\",\n                    \"swatchesInfo\": \"variantColor1:Black F202 ;;;; variantColor3:blue 805 ;;;; variantColor2:Grey F123 ;;;; variantColor5:blue 805 ;;;; variantColor4:Grey F123 ;;;; variantColor6:Blue 031 ;;;; variantImage6:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275892_medium.jpg?v=1611184269&vid=16847227715715 ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275893_medium.jpg?v=1611184327&vid=16847231189123 ;;;; variantId6:34322550358147 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275898_medium.jpg?v=1611184209&vid=16847190294659 ;;;; variantImage5:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275893_medium.jpg?v=1611184327&vid=16847231189123 ;;;; variantId4:34322540429443 ;;;; variantImage4:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1590275898_medium.jpg?v=1611184209&vid=16847190294659 ;;;; variantId5:34322543968387 ;;;; variantId2:34322530631811 ;;;; variantId3:34322538528899 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1124428249_medium.jpg?v=1611184372&vid=16847233613955 ;;;; variantId1:34322518048899 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 11,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/2020-new-trousers-grey-fleece-men-clothes-black-elasticity-warm-thinker-winter-jeans-busines-with-or-no-velvet-2-model-jeans\",\n                    \"fabric\": \"Stripe\",\n                    \"name\": \"New Trousers Fleece Men Clothes Elasticity Warm Thinker Jeans Business\",\n                    \"shortDesc\": \"fabric:fabric:stripe]]>; closure:closure:zipper fly; decoration:decoration:button; ;;;; Brand Name: Odinokov Origin: CN(Origin) Closure Type: Zipper\",\n                    \"category\": \"All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                },\n                {\n                    \"color\": \"Yellow Hoodie Men\",\n                    \"discount\": \"\",\n                    \"hideGroupPrices\": \"\",\n                    \"itemGroupId\": \"5192760328323\",\n                    \"freeShipping\": \"\",\n                    \"storeBaseCurrency\": \"EUR\",\n                    \"inventory_item_id\": \"35904931790979\",\n                    \"price\": \"59.38\",\n                    \"toPrice\": \"\",\n                    \"imageUrl\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173524_medium.jpg?v=1611184275&vid=34322703188099,34322704957571,34322704990339,34322705023107,34322705055875,34322705088643,34322705121411\",\n                    \"currency\": \"EUR\",\n                    \"inStock\": \"yes\",\n                    \"id\": \"34322705055875\",\n                    \"imageHover\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173526_medium.jpg?v=1611184275&vid=34322705383555,34322705416323,34322705449091,34322705481859,34322705514627,34322705547395,34322705580163\",\n                    \"sku\": \"29406380-yellow-hoodie-men-asian-4xl\",\n                    \"brand\": \"klevu-personalisation-demo\",\n                    \"startPrice\": \"56.3\",\n                    \"image\": \"https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173524_medium.jpg?v=1611184275&vid=34322703188099,34322704957571,34322704990339,34322705023107,34322705055875,34322705088643,34322705121411\",\n                    \"deliveryInfo\": \"\",\n                    \"hideAddToCart\": \"\",\n                    \"salePrice\": \"59.38\",\n                    \"swatchesInfo\": \"variantColor1:Yellow Hoodie Men ;;;; variantColor3:White Hoodie Men ;;;; variantColor2:Black Hoodie Men ;;;; variantImage3:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173526_medium.jpg?v=1611184275&vid=16847178432643 ;;;; variantImage2:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173525_medium.jpg?v=1611184275&vid=16847179415683 ;;;; variantId2:34322705154179 ;;;; variantId3:34322705383555 ;;;; variantImage1:https://cdn.shopify.com/s/files/1/0386/6653/5043/products/product-image-1593173524_medium.jpg?v=1611184275&vid=16847180005507 ;;;; variantId1:34322703188099 ;;;;\",\n                    \"weight\": \"\",\n                    \"klevu_category\": \"KLEVU_PRODUCT;Products;;All  @ku@kuCategory@ku@\",\n                    \"totalVariants\": 17,\n                    \"groupPrices\": \"\",\n                    \"url\": \"https://klevu-personalisation-demo.myshopify.com/products/singleroad-mens-hoodies-men-2020-winter-fleece-sweatshirt-harajuku-japanese-streetwear-hip-hop-yellow-hoodie-men-sweatshirts\",\n                    \"size\": \"Asian-4XL\",\n                    \"name\": \"Fleece Sweatshirt\",\n                    \"shortDesc\": \"gender:gender:men; season:season:winter,hoodie,men; closure:closure:none; ;;;; Brand Name: Single Road Origin: CN(Origin) Sleeve Length(cm): Full\",\n                    \"category\": \"All\",\n                    \"typeOfRecord\": \"KLEVU_PRODUCT\"\n                }\n            ],\n            \"filters\": []\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3XlvmT855lGkJOht0nPXg"
  },
  "examples": {
    "languages": [
      {
        "id": "jSU7DlYyJ_eUh63YSP682",
        "code": "{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsSimilar\",\n      \"typeOfRequest\": \"RECS_SIMILAR\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322682183811\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}",
        "language": "json",
        "customLabel": "Request Body (JSON)"
      },
      {
        "id": "8Yg33Te4JzfoWp5yEbmJh",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n  \"recordQueries\": [\n    {\n      \"id\": \"recsSimilar\",\n      \"typeOfRequest\": \"RECS_SIMILAR\",\n      \"settings\": {\n        \"context\": {\n          \"recentObjects\": [\n            {\n              \"typeOfRecord\": \"KLEVU_PRODUCT\",\n              \"records\": [\n                {\n                  \"id\": 34322682183811\n                }\n              ]\n            }\n          ]\n        },\n        \"typeOfRecords\": [\n          \"KLEVU_PRODUCT\"\n        ]\n      }\n    }\n  ],\n  \"context\": {\n    \"apiKeys\": [\n      \"klevu-158755634955912036\"\n    ]\n  }\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "WCDgTsSqAXfiwklk2V174",
        "code": "var data = JSON.stringify({\"recordQueries\":[{\"id\":\"recsSimilar\",\"typeOfRequest\":\"RECS_SIMILAR\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322682183811}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://eucs19v2.ksearchnet.com/cs/v2/search\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "nPW0NIJe-j5R9I5W4BGN0",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n  \\\"recordQueries\\\": [\\n    {\\n      \\\"id\\\": \\\"recsSimilar\\\",\\n      \\\"typeOfRequest\\\": \\\"RECS_SIMILAR\\\",\\n      \\\"settings\\\": {\\n        \\\"context\\\": {\\n          \\\"recentObjects\\\": [\\n            {\\n              \\\"typeOfRecord\\\": \\\"KLEVU_PRODUCT\\\",\\n              \\\"records\\\": [\\n                {\\n                  \\\"id\\\": 34322682183811\\n                }\\n              ]\\n            }\\n          ]\\n        },\\n        \\\"typeOfRecords\\\": [\\n          \\\"KLEVU_PRODUCT\\\"\\n        ]\\n      }\\n    }\\n  ],\\n  \\\"context\\\": {\\n    \\\"apiKeys\\\": [\\n      \\\"klevu-158755634955912036\\\"\\n    ]\\n  }\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://eucs19v2.ksearchnet.com/cs/v2/search\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "0Ih7nieKhHFMl7CRY51j_",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://eucs19v2.ksearchnet.com/cs/v2/search',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"recordQueries\":[{\"id\":\"recsSimilar\",\"typeOfRequest\":\"RECS_SIMILAR\",\"settings\":{\"context\":{\"recentObjects\":[{\"typeOfRecord\":\"KLEVU_PRODUCT\",\"records\":[{\"id\":34322682183811}]}]},\"typeOfRecords\":[\"KLEVU_PRODUCT\"]}}],\"context\":{\"apiKeys\":[\"klevu-158755634955912036\"]}})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "WCDgTsSqAXfiwklk2V174"
  },
  "description": "The end-point is used for retrieving Similar products.",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "similar-products",
  "legacyHash": "gRgQCrW3xaVpxbuFmU9Wj"
}
```
:::

### Try it here!&#x20;

:::Iframe{code="<iframe src=&#x22;https://codesandbox.io/embed/klevu-api-sendbox-4ktfrp?fontsize=14&hidenavigation=0&theme=dark&view=preview&initialpath=?payload=similarProducts&#x22;&#xA;     style=&#x22;width:100%; height:550px; border:0; border-radius: 4px; overflow:hidden;&#x22;&#xA;     title=&#x22;klevu_api sendbox&#x22;&#xA;     allow=&#x22;accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking&#x22;&#xA;     sandbox=&#x22;allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts&#x22;&#xA;     &#xA;   ></iframe>" iframeHeight="550"}

:::


[title] Category Events
[path] Guide/Analytics Tracking/



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/categoryProductViewTracking",
  "name": "Reporting Category Page Views",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "klevu_apiKey",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "klevu_categoryName",
        "type": "string",
        "description": "This is the name of the category being visited. For example, Stackable Rings. The name should not include parent categories."
      },
      {
        "kind": "required",
        "name": "klevu_categoryPath",
        "type": "string",
        "description": "This is the complete hierarchy of the category being visited. For example, Jewellery;Rings;Stackable Rings. Please note the use of a semicolon as the separator between a parent and a child category."
      },
      {
        "kind": "required",
        "name": "klevu_productIds",
        "type": "string",
        "description": "Comma separated list of product IDs being shown on the current page of the category page. For example, P1,P2,P3,P4,P5…\nAll the product IDs listed here are treated as impressions for these products."
      },
      {
        "kind": "optional",
        "name": "klevu_pageStartsFrom",
        "type": "string",
        "description": "Offset of the first product being shown on this page. For example, if you are displaying 30 products per page and if a customer is on the 2nd page, the value here should be 30. If on the 3rd page, it will be 60."
      },
      {
        "kind": "required",
        "name": "klevu_shopperIP",
        "type": "string",
        "description": "IP address of the shopper who viewed the category page.\n\n*If calling from javascript, this is an optional parameter."
      },
      {
        "kind": "optional",
        "name": "klevu_activeFilters",
        "type": "string",
        "children": [],
        "description": "This refers to the filters that were applied during the category page view event. The format for the applied filters is \"<filterKey1>:<filterValue1>;;<filterKey2>:<filterValue2>\". Multiple filters are separated by \";;\". For example, \"style:Underseat Luggage;;color:blue\"."
      },
      {
        "kind": "optional",
        "name": "klevu_abTestId",
        "type": "string",
        "children": [],
        "description": "The unique identifier of the A/B Test."
      },
      {
        "kind": "optional",
        "name": "klevu_abTestVariantId",
        "type": "string",
        "children": [],
        "description": "The unique identifier of the A/B Test Variant."
      },
      {
        "name": "klevu_shopperIP_v4",
        "kind": "optional",
        "type": "string",
        "description": "IPv4 address of the shopper who viewed a category page.",
        "children": []
      },
      {
        "name": "klevu_shopperIP_v6",
        "kind": "optional",
        "type": "string",
        "description": "IPv6 address of the shopper who viewed a category page.",
        "children": []
      },
      {
        "name": "data_protection",
        "kind": "optional",
        "type": "Boolean",
        "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true.",
        "children": []
      },
      {
        "name": "klevu_uuid",
        "kind": "optional",
        "type": "string",
        "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid",
        "children": []
      },
      {
        "name": "klevu_country",
        "kind": "optional",
        "type": "string",
        "description": "2-digit country code of the shopper who viewed a category. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes",
        "children": []
      },
      {
        "name": "klevu_city",
        "kind": "optional",
        "type": "string",
        "description": "City name of the shopper who viewed a category.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "mMCwmnqgHyEFJv4j56P1h",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/categoryProductViewTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=tees&klevu_categoryPath=Mens%253BShoes%2520and%2520Trainers%253BSneakers&klevu_productIds=31366450446398,31366450380862,31366479020094,31366447038526,31366447923262,31366448382014&klevu_pageStartsFrom=0',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "bBzdFXkvvZ09pieoDzhwC",
        "code": "// WARNING: For GET requests, body is set to null by browsers.\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = true;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"GET\", \"https://stats.ksearchnet.com/analytics/categoryProductViewTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=tees&klevu_categoryPath=Mens%253BShoes%2520and%2520Trainers%253BSneakers&klevu_productIds=31366450446398%2C31366450380862%2C31366479020094%2C31366447038526%2C31366447923262%2C31366448382014&klevu_pageStartsFrom=0\");\n\nxhr.send();",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "3ikKepqX_FFNMIW40CzKP",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/categoryProductViewTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=tees&klevu_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers&klevu_productIds=31366450446398,31366450380862,31366479020094,31366447038526,31366447923262,31366448382014&klevu_pageStartsFrom=0\")\n  .method(\"GET\", null)\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "C6uOme2HcXhNgZOFPqfkD",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://stats.ksearchnet.com/analytics/categoryProductViewTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=tees&klevu_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers&klevu_productIds=31366450446398,31366450380862,31366479020094,31366447038526,31366447923262,31366448382014&klevu_pageStartsFrom=0',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "bBzdFXkvvZ09pieoDzhwC"
  },
  "description": "Use this API endpoint to submit category page views activity:\n1.  When the category response is received\n2. And also when a facet is clicked (triggering a follow up query) \n\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-category-page-views",
  "legacyHash": "xXwY19SNxXJHv638AIMn_"
}
```
:::



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://{{ Analytics_URL }}/analytics/categoryProductClickTracking",
  "name": "Reporting Category Product Clicks",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "klevu_apiKey",
        "type": "string",
        "description": "This is your Klevu JS API Key."
      },
      {
        "kind": "required",
        "name": "klevu_categoryName",
        "type": "string",
        "description": "This is the name of the category being visited. For example, Stackable Rings. The name should not include parent categories."
      },
      {
        "kind": "required",
        "name": "klevu_categoryPath",
        "type": "string",
        "description": "This is the complete hierarchy of the category being visited. For example, Jewellery;Rings;Stackable Rings. Please note the use of a semicolon as the separator between a parent and a child category."
      },
      {
        "kind": "required",
        "name": "klevu_productId",
        "type": "string",
        "description": "This is the Klevu ID of the clicked product. eg. 54321-12345."
      },
      {
        "kind": "required",
        "name": "klevu_productGroupId",
        "type": "string",
        "description": "This is the parent ID of the clicked product. eg. 54321. For compound products with a parent and multiple child/variant products, this is the common ID which ties the products together. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "required",
        "name": "klevu_productVariantId",
        "type": "string",
        "description": "This is the child/variant ID of the clicked product. eg. 12345. For compound products with a parent and multiple child/variant products, this is the ID of the specific variant. For simple products, please specify the same as klevu_productId."
      },
      {
        "kind": "optional",
        "name": "klevu_productName",
        "type": "string",
        "description": "Name of the product that was clicked."
      },
      {
        "kind": "optional",
        "name": "klevu_productUrl",
        "type": "string",
        "description": "URL of the product that was clicked."
      },
      {
        "kind": "optional",
        "name": "klevu_productSku",
        "type": "string",
        "description": "SKU code of the product that was clicked."
      },
      {
        "kind": "optional",
        "name": "klevu_salePrice",
        "type": "string",
        "description": "Decimal sale price of the product that was clicked."
      },
      {
        "kind": "optional",
        "name": "klevu_productRatings",
        "type": "Number",
        "description": "A decimal rating value between 0 and 5 of the product that was clicked."
      },
      {
        "kind": "optional",
        "name": "klevu_productPosition",
        "type": "Integer",
        "description": "Position of the product on the category page when it was clicked. For example, the value would be 0 if it is the first product on the first page. The value will be 30, if it is the first product on the 2nd page with 30 products being displayed per page."
      },
      {
        "kind": "required",
        "name": "klevu_shopperIP",
        "type": "string",
        "description": "IP address of the shopper who clicked the product(s).\n\n*If calling from javascript, this is an optional parameter."
      },
      {
        "kind": "optional",
        "name": "klevu_activeFilters",
        "type": "string",
        "children": [],
        "description": "This refers to the filters that were applied during the product clicked event. The format for the applied filters is \"<filterKey1>:<filterValue1>;;<filterKey2>:<filterValue2>\". Multiple filters are separated by \";;\". For example, \"style:Underseat Luggage;;color:blue\"."
      },
      {
        "kind": "optional",
        "name": "klevu_abTestId",
        "type": "string",
        "description": "The unique identifier of the A/B Test."
      },
      {
        "kind": "optional",
        "name": "klevu_abTestVariantId",
        "type": "string",
        "description": "The unique identifier of the A/B Test Variant.\n"
      },
      {
        "name": "klevu_shopperIP_v4",
        "kind": "optional",
        "type": "string",
        "description": "IPv4 address of the shopper who clicked a product.",
        "children": []
      },
      {
        "name": "klevu_shopperIP_v6",
        "kind": "optional",
        "type": "string",
        "description": "IPv6 address of the shopper who clicked a product.",
        "children": []
      },
      {
        "name": "data_protection",
        "kind": "optional",
        "type": "Boolean",
        "description": "If set to false, Klevu's backend do not obtain the shoppers' IP address. The default value is true.",
        "children": []
      },
      {
        "name": "klevu_uuid",
        "kind": "optional",
        "type": "string",
        "description": "Universally unique identifier generated by Klevu, it can be also considered as session id. Please obtain UUID using end-point: https://docs.klevu.com/apis/uuid",
        "children": []
      },
      {
        "name": "klevu_country",
        "kind": "optional",
        "type": "string",
        "description": "2-digit country code of the shopper who searched a term. Valid codes can be found at https://developers.google.com/hotels/hotel-prices/dev-guide/country-codes",
        "children": []
      },
      {
        "name": "klevu_city",
        "kind": "optional",
        "type": "string",
        "description": "City name of the shopper who clicked a product.",
        "children": []
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "<data>\n    <response>SUCCESS</response>\n</data>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "mMCwmnqgHyEFJv4j56P1h",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://stats.ksearchnet.com/analytics/categoryProductClickTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=Sneakers&klevu_categoryPath=Mens%253BShoes%2520and%2520Trainers%253BSneakers&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%2520Trainers&klevu_productUrl=https%253A%252F%252Fyour.website.com%252Fproduct-url&klevu_productSku=ABC-123&klevu_salePrice=123.45&klevu_productRatings=3&klevu_productPosition=7&klevu_abTestId=9c8bm3o1-osjgoqn9-9mbjudid&klevu_abTestVariantId=if92kdmc-98ckcj89-98cjcd9d',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'GET',\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "bBzdFXkvvZ09pieoDzhwC",
        "code": "\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"GET\", 'https://stats.ksearchnet.com/analytics/categoryProductViewTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=tees&klevu_categoryPath=Mens%253BShoes%2520and%2520Trainers%253BSneakers&klevu_productIds=31366450446398,31366450380862,31366479020094,31366447038526,31366447923262,31366448382014&klevu_pageStartsFrom=0');\n\nxhr.send();",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "3ikKepqX_FFNMIW40CzKP",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nRequest request = new Request.Builder()\n  .url(\"https://stats.ksearchnet.com/analytics/categoryProductClickTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=Sneakers&klevu_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%20Trainers&klevu_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url&klevu_productSku=ABC-123&klevu_salePrice=123.45&klevu_productRatings=3&klevu_productPosition=7&klevu_abTestId=9c8bm3o1-osjgoqn9-9mbjudid&klevu_abTestVariantId=if92kdmc-98ckcj89-98cjcd9d\")\n  .method(\"GET\", null)\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "C6uOme2HcXhNgZOFPqfkD",
        "code": "var request = require('request');\nvar options = {\n  'method': 'GET',\n  'url': 'https://stats.ksearchnet.com/analytics/categoryProductClickTracking?klevu_apiKey=klevu-1234567890&klevu_categoryName=Sneakers&klevu_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers&klevu_productId=54321-12345&klevu_productGroupId=54321&klevu_productVariantId=12345&klevu_productName=Smart%20Trainers&klevu_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url&klevu_productSku=ABC-123&klevu_salePrice=123.45&klevu_productRatings=3&klevu_productPosition=7&klevu_abTestId=9c8bm3o1-osjgoqn9-9mbjudid&klevu_abTestVariantId=if92kdmc-98ckcj89-98cjcd9d',\n  'headers': {\n  }\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "bBzdFXkvvZ09pieoDzhwC"
  },
  "description": "Use this API endpoint to submit the product clicks from category page results.\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-category-product-clicks",
  "legacyHash": "p_x2ERCBm5K1bEb9qwgzG"
}
```
:::



:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://config-cdn.ksearchnet.com/abtest/public/usage/{{ Your Klevu apiKey }}/",
  "name": "Reporting A/B Test Variant View",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [
      {
        "kind": "required",
        "name": "sourceId",
        "type": "string",
        "description": "The unique identifier of the element to which the A/B Test ID and Variant are assigned to. In this case, it will be a Category name."
      },
      {
        "kind": "required",
        "name": "abTestId",
        "type": "string",
        "description": "The unique identifier of the A/B Test."
      },
      {
        "kind": "required",
        "name": "abTestVariantId",
        "type": "string",
        "description": "The unique identifier of the A/B Test Variant."
      },
      {
        "kind": "required",
        "name": "type",
        "type": "string",
        "description": "The type of element to which an A/B Test will be assigned. For now, will be “CAT_NAV”."
      }
    ],
    "headerParameters": [],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "DdxomvWNISlr_Jx48gHQd",
        "code": "",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "DdxomvWNISlr_Jx48gHQd"
  },
  "examples": {
    "languages": [
      {
        "id": "nUESRs-n5VrHA1aB9gv6Y",
        "code": "{\n    \"sourceId\": \"womens;jeans\",\n    \"abTestId\": \"9c8bm3o1-osjgoqn9-9mbjudid\",\n    \"abTestVariantId\": \"if92kdmc-98ckcj89-98cjcd9d\", \n    \"type\": \"CAT_NAV\"\n}",
        "language": "json",
        "customLabel": ""
      },
      {
        "id": "mMCwmnqgHyEFJv4j56P1h",
        "code": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n  CURLOPT_URL => 'https://config-cdn.ksearchnet.com/abtest/public/usage/klevu-158755634955912036/',\n  CURLOPT_RETURNTRANSFER => true,\n  CURLOPT_ENCODING => '',\n  CURLOPT_MAXREDIRS => 10,\n  CURLOPT_TIMEOUT => 0,\n  CURLOPT_FOLLOWLOCATION => true,\n  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n  CURLOPT_CUSTOMREQUEST => 'POST',\n  CURLOPT_POSTFIELDS =>'{\n    \"sourceId\": \"womens;jeans\",\n    \"abTestId\": \"9c8bm3o1-osjgoqn9-9mbjudid\",\n    \"abTestVariantId\": \"if92kdmc-98ckcj89-98cjcd9d\", \n    \"type\": \"CAT_NAV\"\n}',\n  CURLOPT_HTTPHEADER => array(\n    'Content-Type: application/json'\n  ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n",
        "language": "php",
        "customLabel": ""
      },
      {
        "id": "bBzdFXkvvZ09pieoDzhwC",
        "code": "var data = JSON.stringify({\"sourceId\":\"womens;jeans\",\"abTestId\":\"9c8bm3o1-osjgoqn9-9mbjudid\",\"abTestVariantId\":\"if92kdmc-98ckcj89-98cjcd9d\",\"type\":\"CAT_NAV\"});\n\nvar xhr = new XMLHttpRequest();\nxhr.withCredentials = false;\n\nxhr.addEventListener(\"readystatechange\", function() {\n  if(this.readyState === 4) {\n    console.log(this.responseText);\n  }\n});\n\nxhr.open(\"POST\", \"https://config-cdn.ksearchnet.com/abtest/public/usage/klevu-158755634955912036/\");\nxhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\nxhr.send(data);",
        "language": "javascript",
        "customLabel": ""
      },
      {
        "id": "3ikKepqX_FFNMIW40CzKP",
        "code": "OkHttpClient client = new OkHttpClient().newBuilder()\n  .build();\nMediaType mediaType = MediaType.parse(\"application/json\");\nRequestBody body = RequestBody.create(mediaType, \"{\\n    \\\"sourceId\\\": \\\"womens;jeans\\\",\\n    \\\"abTestId\\\": \\\"9c8bm3o1-osjgoqn9-9mbjudid\\\",\\n    \\\"abTestVariantId\\\": \\\"if92kdmc-98ckcj89-98cjcd9d\\\", \\n    \\\"type\\\": \\\"CAT_NAV\\\"\\n}\");\nRequest request = new Request.Builder()\n  .url(\"https://config-cdn.ksearchnet.com/abtest/public/usage/klevu-158755634955912036/\")\n  .method(\"POST\", body)\n  .addHeader(\"Content-Type\", \"application/json\")\n  .build();\nResponse response = client.newCall(request).execute();",
        "language": "java",
        "customLabel": ""
      },
      {
        "id": "C6uOme2HcXhNgZOFPqfkD",
        "code": "var request = require('request');\nvar options = {\n  'method': 'POST',\n  'url': 'https://config-cdn.ksearchnet.com/abtest/public/usage/klevu-158755634955912036/',\n  'headers': {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\"sourceId\":\"womens;jeans\",\"abTestId\":\"9c8bm3o1-osjgoqn9-9mbjudid\",\"abTestVariantId\":\"if92kdmc-98ckcj89-98cjcd9d\",\"type\":\"CAT_NAV\"})\n\n};\nrequest(options, function (error, response) {\n  if (error) throw new Error(error);\n  console.log(response.body);\n});\n",
        "language": "nodejs",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "bBzdFXkvvZ09pieoDzhwC"
  },
  "description": "Use this API endpoint to report which A/B test variant is viewed.\n\n",
  "currentNewParameter": {
    "label": "Query Parameter",
    "value": "queryParameters"
  },
  "autoGeneratedAnchorSlug": "reporting-ab-test-variant-view",
  "legacyHash": "KJknw4xTbARU8YaCcLfrt"
}
```
:::


[title] URL Redirects
[path] Guide/Dashboard Settings/

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://js.klevu.com/klevu-js-v1/klevu-js-api/{{JS_API_KEY}}-maps.json",
  "name": "URL Redirects ",
  "method": "GET",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "JS_API_KEY",
        "type": "string",
        "description": "Your public Klevu JS API Key.\n"
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "Y1Vx38kZQPtiLmsufAFM_",
        "code": "{\n    \"klevu_autoCorrectMap\": [],\n    \"klevu_keywordUrlMap\": [\n        {\n            \"keywords\": [\n                \"new test\"\n            ],\n            \"url\": \"https://www.google.com/\"\n        },\n        {\n            \"keywords\": [\n                \"rücksendung\"\n            ],\n            \"url\": \"https://www.klevu.com/\"\n        },\n        {\n            \"keywords\": [\n                \"redirect-test\",\n                \"rucksendung\"\n            ],\n            \"url\": \"http://www.google.com\"\n        }\n    ]\n}",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Y1Vx38kZQPtiLmsufAFM_"
  },
  "examples": {
    "languages": [
      {
        "id": "3AdeysJML2Tq9WYHSdiJU",
        "code": "curl --location --request GET 'https://js.klevu.com/klevu-js-v1/klevu-js-api/klevu-14728819608184175-maps.json'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "3AdeysJML2Tq9WYHSdiJU"
  },
  "description": "The end-point to retrieve the list of URL redirects added in Klevu dashboard. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "url-redirects",
  "legacyHash": "uFN0pI-f3BZCXFZPdr81Q"
}
```
:::


[title] Smart Recommendations
[path] Guide/

Product recommendations powered by search data helps merchants offer relevant and personal shopping experiences, improving customer experience site-wide.

## Getting Started

- Understanding Klevu's API [Overview](docId\:cZeodl0sKcuv-18IPupLr) format and prerequisites.
- Implementing various product recommendation banners using [Overview](docId\:sw_cGq6HOf6vSnAUpCQ0Z)&#x20;
- Integrate [Analytics Events](docId\:v2qekd02znWeMtqJqq9Mj)&#x20;


[title] Overview
[path] Guide/Smart Recommendations/

Klevu can also make AI-powered Recommendations to your customers, for example, You May Also Like, Customers Also Bought/Viewed, Hot/Trending Products, etc.

The approach is quite similar to a record search, however, instead of providing the search term your customer has entered, you will specify the type of recommendation with some context.

There are two main differences between a record search query and a recommendation query:

the value of typeOfRequest becomes the type of recommendation, eg. "RECS\_ALSO\_VIEWED". instead of a search term, we specify a context with data to base the recommendation on.  Most of the request parameters available for a record search can also be used for recommendations, including personalisation, result fine-tuning, filtering results, and applying any number of search preferences.




[space] Klevu Headless SDK (/headless-sdk)

[title] Modifier Functions
[path] Guide/

Modifier functions are helpers that change the way query functions work. They are place in the end of query functions that support them. Almost all query functions support modifier functions. There can be any amount of modifer functions placed in one query function.

Here is short description of every modifer function. Full reference can be found from @klevu/core reference documentation.

| Modifier                        | Description                                                                                          |
| ------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `listFilters()`                 | List all filters that given search result has                                                        |
| `applyFilters()`                | Applies selected filters to query                                                                    |
| `applyFilterWithManager()`      | Applies filters that's state is managed by `FilterManager`                                           |
| `fallback()`                    | When query returns less results than fallback treshold then additional fallback query is sent        |
| `boostWithKeywords()`           | Boost or deboost results with keywords                                                               |
| `boostWithRecords()`            | Boost or deboost certain products in the result by id                                                |
| `boostWithFilters()`            | Boost or deboost results based on a filters                                                          |
| `boostWithFilterManager()`      | Boost or deboost results based in selection in filter manager                                        |
| `personalisation()`             | Enable personalisation to the query. Automatically applies last visited products                     |
| `include()`                     | Force include given id's in the result                                                               |
| `top()`                         | Force return given id's as first items on results                                                    |
| `sendSearchEvent()`             | When user takes action to search something this should be used                                       |
| `sendMerchandisingViewEvent()`  | Should be used with `categoryMerchandising()` query to send view event of merchandising              |
| `sendRecommendationViewEvent()` | Should be used with all recommendation queries. Send a analytical data about recommendation to Klevu |
| `debug()`                       | Prints query results to console                                                                      |
| `raw()`                         | Send any request to Klevu API. Check API documentation for properties.                               |


[title] SSR result packing and hydration
[path] Guide/

Typically SSR frameworks (Next, Nuxt, Remix, etc) will transfer data from backend to frontend in JSON format. Passing KlevuFetch result object to frontend won't work as it is filled with functions that help the usage of results.

There is an option to just pass raw JSON with `result.apiResponse` and build your logic on top of that.

If you wish to keep using helper functions provided in results you can use `KlevuPackFetchResult()` function to pack result like:

```javascript
const result = await KlevuFetch(search("hello world"))
const dataToTransferFrontend = KlevuPackFetchResult(result)
```

And then you can hydrate it in frontend with `KlevuHydratePackedFetchResult()` function.

```javascript
const resultObject = KlevuHydratePackedFetchResult(dataToTransferFrontend, [
  search("hello world"),
])
```

It's important to note that the second parameter of `KlevuHydratePackedFetchResult()` has to be the same as in backend call. You can create query functions in a separate file that can be called both in frontend and backend. For example:

```javascript
// file: myquery.ts
// a bit more compilicated query. Search term can be read in backend
// from request parameters and in frontend it could be in url parameters
const myQuery = (searchTerm: string, manager: FilterManager) => [
  search(
    searchTerm,
    {},
    listFilters(),
    applyFilterwithManager(manager),
    boostWithKeyword({ keyword: "foobar", weight: 1.2 })
  ),
  suggestions(searchTerm),
]

// file: backend.ts
// in backend manager is not used to set anything so it can be just instanciated as param
const result = await KlevuFetch(myQuery("hello world", new FilterManager()))
const dataToTransferFrontend = KlevuPackFetchResult(result)

// file: frontend.ts
// in frontend we usually want to change and set filters with manager so it's used as separate variable
const manager = new FilterManager()
const resultObject = KlevuHydratePackedFetchResult(
  dataToTransferFrontend,
  myQuery("hello world", manager)
)
console.log(manager.options)
```

Example of using this technique can be found from Shopify Hydrogen example in [here.](https://github.com/klevultd/frontend-sdk/blob/v1.3.0/examples/hydrogen/src/routes/search.server.tsx)

[title] Guide
[path] /

The [@klevu/core](docId\:TcMCtFIYSJtuJNg05T4_D) reference section will list all the available functions, enums, etc., for the library, but we wanted to call out a few of the most common and important ones here. &#x20;

### klevuFetch

As mentioned in the [Quickstart](docId\:FI-QiGRFSn06qmlQ6rCBs) queries to Klevu are made with the **klevuFetch** function. Inside KlevuFetch you can provide any amount of [Query Functions](docId\:ZUyEfY2EcMhBLYQUSF0vk)  as parameters. Within the query functions you call, you are also able to pass any number of [Modifier Functions](docId:71mywvWez1Pw_nilxv79h).&#x20;

For example within our React example, on the search landing page we pass in a search query function along with two modifier functions.

:::CodeblockTabs
```javascript
const result = await KlevuFetch(
  search(
    query.get("q"),
    {
      id: "search",
      limit: 36,
      sort: sorting,
    },
    listFilters({
      rangeFilterSettings: [
        {
          key: "klevu_price",
          minMax: true,
        },
      ],
      filterManager: manager,
    }),
    applyFilterWithManager(manager)
  ),
  suggestions(
    query.get("q"), 
    {
      id: suggestions,
    }
  ),
)
const searchResult = result.queriesById("search")
  clickManager = searchResult.getSearchClickManager()

  setProducts(searchResult?.records ?? [])
  setSuggestions(
    result.suggestionsById("suggestions")?.suggestions.map((i) => i.suggest) ??
      []
  )
```

```typescript
```
:::

In the above example we pass in the search and suggestions query functions to klevuFetch. In the search query function we then pass in the search term, options (id, limit, sorting, type of search, etc), and two modifier functions (listFilters and applyFilterWithManager).&#x20;

Continue to the next section to learn more about Query Functions and Modifier Functions.

### Result Object

Once you've made your queries through klevuFetch, a single response object is returned. Because you are able to request more than one search, each search should have an ID. These IDs can then be used to reference the results of each search using either `queriesById` or  `suggestionsById`

In the above code example, the `result` variable is the result object.&#x20;

Once you have the query you want to work with, you will find many helpful functions available to such as generating click handlers to send analytics back to Klevu, or requesting more records/data when using a limit.&#x20;

### KlevuKMCSettings Utility Function

Every Klevu account comes with a feature-rich admin panel called KMC (Klevu Merchant Center). In order to fetch many of the settings found in KMC, you call KlevuKMCSettings() asynchronously as shown below.&#x20;

:::CodeblockTabs
```javascript
const kmcSettings = await KlevuKMCSettings();
console.log(kmcSettings);
```

JSON Response

```json
{
  "root": {
    "klevu_showBannerAds": true,
    "klevu_multiSelectFilters": true,
    "klevu_abTestActive": false,
    "klevu_userAnalyticsDomain": "stats.ksearchnet.com",
    "klevu_uc_userOptions": {
      "addToCartButton": "Add to Cart",
      "showRolloverImage": false,
      "showProductSwatches": false,
      "enablePersonalisationInCatNav": false,
      "showRatingsCountOnCategoryPage": false,
      "noResultsOptions": {
        "messages": [],
        "banners": []
      },
      "noImageUrl": "/klevu-js-v1/img-1-1/place-holder.jpg",
      "showRatingsOnCategoryPage": true,
      "enablePersonalisationInSearch": false,
      "isFullImageUrlProvided": false,
      "showSearchBoxOnLandingPage": true,
      "priceInterval": "500",
      "showRatingsCountOnSearchResultsLandingPage": false,
      "showRecentlyViewedItems": false,
      "showTrendingProducts": false,
      "showRatingsOnQuickSearches": true,
      "showRatingsCountOnQuickSearches": false,
      "showRatingsOnSearchResultsLandingPage": true,
      "landingFilterPosition": "left",
      "showFiltersInMobile": true
    },
    "klevu_cmsAnalyticsDomain": "stats.ksearchnet.com",
    "klevu_showOutOfStock": false,
    "klevu_webStoreLanguage": "en",
    "klevu_logoFreeSearch": true,
    "klevu_layoutView": "grid",
    "klevu_showPopuralTerms": false,
    "klevu_showProductCode": false,
    "klevu_showPopularSearches": true,
    "klevu_cmsApiKey": "klevu-164314778912414722",
    "klevu_categorySearchEnabled": true,
    "klevu_showPriceSlider": true,
    "klevu_addToCartEnabled": true,
    "klevu_cmsEnabled": true,
    "klevu_filtersOnLeft": true,
    "klevu_showPrices": true,
    "klevu_isSearchActive": true,
    "klevu_filtersEnabled": true,
    "klevu_fluidLayoutEnabled": true,
    "klevu_cmsSearchDomain": "eucs28.ksearchnet.com",
    "klevu_lookForDataInSameFeed": true,
    "klevuLayoutVersion": "-1-1",
    "klevu_loadMapFile": true,
    "klevu_layoutType": "slim",
    "klevu_apiDomain": "api.ksearchnet.com",
    "klevu_userSearchDomain": "eucs28.ksearchnet.com",
    "klevu_showRecentSerches": true,
    "klevu_userJavascriptDomain": "js.klevu.com"
  },
  "banner": {
    "klevu_banner": [
      {
        "showForTerms": null,
        "showOnLandingPage": true,
        "redirectUrl": "https://uvalktopia.myshopify.com/pages/red-shoes-page",
        "showOnQuickSearch": false,
        "endDate": "",
        "bannerName": "Red Shoes",
        "position": "bottom",
        "bannerRef": 13757,
        "bannerImg": "https://cdn.shopify.com/s/files/1/0622/9039/5389/files/treesbg.jpg?v=1678465037",
        "showOnCategoryPage": false,
        "startDate": "2023/3/10"
      }
    ]
  },
  "maps": {
    "klevu_autoCorrectMap": [],
    "klevu_keywordUrlMap": [
      {
        "keywords": [
          "red shoe"
        ],
        "url": "https://uvalktopia.myshopify.com/products/palladium-pallatech-hi-tx-chevron"
      }
    ]
  }
}
```
:::

As you can see, not only do you get the majority of settings, you also get access to Promotional Banners, URL Redirects and more.&#x20;

[title] Filter Manager
[path] Guide/

Filter Manager is a helper class that takes care of the state of filters. What filters are currently selected and what should be sent. It can be passed to `listFilters()` and then the result is automatically applied to the state. Modifier `applyFilterWithManager()` can base used to apply the current state of filters to query.

Here is an pseudo code example how to use filter manager. First there is initialization and the search:

```javascript
import { 
  KlevuFetch, 
  search, // search query function
  listFilters, // list filter modifier
  applyFilterWithManager, // apply filters modifier
  FilterManager  // the manager
} from "@klevu/core"

// first initialize filter manager. You can do it in global scope or your frameworks component initialization. 
const manager = new FilterManager()

// This is the function you would be calling to make the search
async function mySearch() {
  const result = await KlevuFetch(
    search(
      "hoodies", // search term
      {}, // search parameters
      listFilters({
        filterManager: manager // pass manager to list filters so that it will be populated by results
      }),
      applyFilterWithManager(manager) // when requesting filters use managers current state. In first run its empty.
    )
  )
}
```

Now you have tools to manage filters with FilterManager. To render currently available filters you can use `manager.options` and `manager.sliders`. Sliders include numerical values like price.

```javascript
for (const option of manager.options) {
    console.log(option) // you render code
}
```

To toggle between options you can use toggleOption method.

```javascript
manager.toggleOption(option.key, option.name)
```

## Event

This will change the state of option selection in the filter manager. Now you have to just call `mySearch()` again to fetch results of changed state. You can do this directly by calling the function or listening a [Events (analytics)](docId\:Wj_5A-1SFBWhiq45QVvLQ)&#x20;

```javascript
import { KlevuDomEvents } from "@klevu/core" // Add KlevuDomEvents enumeration to project

// Function to run when filter selection is updated
const handleFilterUpdate = () => {
  mySearch()
}

// Attach event listener
document.addEventListener(
  KlevuDomEvents.FilterSelectionUpdate,
  handleFilterUpdate
)

// Don't forget remove event listener in your component destructor
document.removeEventListener(handleFilterUpdate)
```

## Clearing all selections

To clear all or single category option selections you can use  `clearOptionSelections` function.

```javascript
manager.clearOptionSelections("Size") // To clear all selections in "Size" option
manager.clearOptionSelections() // To clear all selections
```

## Exporting and importing selections from URL

FilterManager has methods to load current state into URL query parameters and a method to load current&#x20;

```javascript
manager.toURLParams(); // returns query string. For example o_color=red
manager.readFromURLParams(new URLSearchParams("o_color=red")); // reads parameters from a string
```


[title] Events (analytics)
[path] Guide/

Klevu collects and processes user interaction data through machine learning to drive search, category, and recommendation results.&#x20;

There are 4 types of events available in the Frontend SDK:

- Result Object Events
  - Event handler functions returned by search requests made through KlevuFetch.
- Search Modifier Events
  - Events that are submitted when searches are being made within KlevuFetch.
- DOM Events
  - Events that are fired by the Frontend SDK to trigger your event handler code.
- Custom Events
  - Low level interface to send your events to Klevu

In typical application you should use Result Object events to pass data to Klevu, Search Modifier Events to send information about user views and listen DOM events for changes made by SDK. Lastly if you are not using Shopify, Magento or BigCommerce connectors you need to pass checkout event to Klevu.

## Result Object Events

View the [Result Object](docId:3GzH10bIAvwZoKq3_g11j) page to learn more about Result Object click events.  It is the easiest way to implement data passing to Klevu.

## Search Modifier Events

Result Object has events for sending click information to Klevu. On top of this information Klevu requires view events. These events should be sent when user views search result, merchendising page or recommendation banner.&#x20;

Typically requests should be implemented to all KlevuFetch calls. Only exception is that when implementing "Quicksearch" bar (a search bar on top of page that shows results right away) it should **not**  send these events. It should be sent only when user clicks into search results page and this is done by the `getSearchClickSendEvent() `  helper in result object.&#x20;

- [sendSearchEvent()](https://docs.klevu.com/klevucore-reference/sendsearchevent): Modifier that should be used on KlevuFetch on search result page.
- [sendMerchendisingViewEvent()](https://docs.klevu.com/klevucore-reference/sendmerchandisingviewevent): Modifier that should be sent when merchendising page is displayed.&#x20;
- [sendRecommendationViewEvent()](https://docs.klevu.com/klevucore-reference/sendrecommendationviewevent): Modifer that should be sent with recommendation request like "kmcRecommendation" or "similarProducts"

## DOM Events

SDK Core sends a DOM events that any browser library could listen and act on the events. All events are attached to document. KlevuDomEvents enumeration is exposed from the library and it's quite simple to listen. For example:


:::CodeblockTabs
```javascript
import { KlevuDomEvents } from "@klevu/core"

// Function to run when filter selection is updated
const handleFilterUpdate = () => {
  console.log("Filter updated")
}

// Attach event listener
document.addEventListener(
  KlevuDomEvents.FilterSelectionUpdate,
  handleFilterUpdate
)

// Don't forget remove event listener in your component destructor
document.removeEventListener(handleFilterUpdate)
```

```typescript
```
:::

Global custom document events that @klevu/core sends

| Event Type            | Description                                     |
| --------------------- | ----------------------------------------------- |
| LastSearchUpdate      | When list of last searched terms update         |
| FilterSelectionUpdate | When filter manager selection has changed       |
| ClickEventSent        | When any click event has been fired on the page |

## Custom Events

`KlevuEvents` class is low level solution to pass events to Klevu backend.

Custom events in the Klevu Headless SDK represent events that are not tied to the Result Object returned by a call to KlevuFetch or dispatched via DOM Events.&#x20;

These events include:

- Search done
- Search product click
- Merchendising view
- Merchendising product click
- Recommendation view
- Recommendation product click
- Buy/Purchase


[title] Reference
[path] /


[title] Klaviyo integration with SDK
[path] Examples/

# Sending Klevu Events to Klaviyo

For Klaviyo integration you need to build click event capturing and use Klaviyo libraries to send the data to Klaviyo. This example shows how to create integration similar to what TemplateJS implements.

Way the Klaviyo-Klevu TemplateJS integration works is that when user has searched something and then clicks a product then searched term and clicked product is sent to Klaviyo. For this to work we need to extract little bit more information about the product and search metadata for it to be easier to create rules in Klaviyo. For this we have implemented `annotationsById()` function to Result Object.

Here is generic pseudo code of how things should work in your code.&#x20;

```javascript
// first reference result object in your code somewhere. In state or context
let resultObject

// function to enable analytics for Klevu
let clickEvent

// then call basic search in your input
async function search() {
    const result = await KlevuFetch(search("hoodies", { id: "search" }))
    resultObject = result.queriesById("search")

    // its good idea to get Klevu analytical events at the same time
    clickEvent = result.queriesById("search").getSearchClickSendEvent()
}

// then in your click function
async function productClick(klevuProduct) {
    //annotations take productId from results and language which to use get annotations in 
    const annotations = await resultObject.annotationsById(klevuProduct.id, 'en')

    // here call the Klaviyo API JS with your custom event data
    // ...

    // Remember to send clickEvents to Klevu too!
    clickEvent(klevuProduct.id)
}
```

Now you can build a Klaviyo analytics event with this annotations data. Example of event that is used in TemplateJS can be found in [vanillajs example in here](https://github.com/klevultd/frontend-sdk/blob/master/examples/vanillajs/quicksearch_klaviyo.ts#L62).

Information on how to send event data to Klaviyo can be found from [Klaviyo JavaScript API documentation](https://developers.klaviyo.com/en/docs/javascript-api).

# Using Klaviyo for segmentation&#x20;

To enable the Klaviyo integration for segmentation in Klevu Recommendations using the SDK, set **enableKlaviyoConnector** to **true** in KlevuConfig.init.

```javascript
KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  enableKlaviyoConnector: true, //To enable Klaviyo integration for segmentation in Recommendations
})
```

Setting **enableKlaviyoConnector&#x20;**&#x74;o **true** will make all the necessary internal configuration changes for Klevu Recommendations to work with Klaviyo segments.

You should consider using this feature with Data Protection settings if there is a need to meet any legal requirements. If Data Protection is enabled, then no user data will be stored unless the consent is given.

Check [Data Protection](docId:5egmkue-DO5kCdLaucErb) for more information.

[title] Result Object
[path] Guide/

`KlevuFetch()` result object contains raw API response and handy helpers to work with the results. For example use `suggestionsById()` to fetch suggestions results and `queriesById()` for search results.&#x20;

```javascript
// Example search the user made
let searchTerm = "blue dress";

let searchResultProducts = [];
let suggestionResultProducts = [];
let searchNextFunc;
let searchClickManager;
let setShowMore = false;

// The Result Object is what is returned from KlevuFetch
const resultObject = await KlevuFetch(
    search(searchTerm, {
        // not required as for default it's the same.
        id: "search", 
        fields: ["name", "price", "url", "category"],
    }),
    suggestions(searchTerm, {
        // not required. as default it's the same.
        id: "suggestions", 
    })
);
```

`queriesById()` result contains metadata for query, getPage(), the result records and possible event functions for providing click events to search, category merchandising and recommendations.&#x20;

```javascript
const suggestionResult = resultObject.suggestionsById("suggestions"));
const searchResult = resultObject.queriesById("search"));

// array of products
suggestionResultProducts = suggestionResult.suggestions;

// array of products
searchResultProducts = searchResult.records;

// either a function or false if no more results
searchNextFunc = searchResult.getPage;

```

Calling these event functions returns a function to use to send events to Klevu.&#x20;

## Get Page Function Examples

`getPage()` is a nice helper to fetch the next results set or certain page of results set with the same queries and modifiers. &#x20;

You can use `hasNextPage()` method to check if there are more pages available. Passing `pageIndex` parameter to `getPage()` allows you to fetch records for certain page.

```javascript
const fetchMore = async () => {
    const nextRes = await searchNextFunc();

    const searchResult = nextRes.queriesById("search");

    searchResultProducts = searchResult?.records ?? [];
    searchNextFunc = searchResult.getPage
    setShowMore(Boolean(searchResult.hasNextPage()))
}
```

[ReactJS SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx)
[VueJS Home.vue](https://github.com/klevultd/frontend-sdk/blob/master/examples/vue/src/views/Home.vue)

## Get banners related to the search

`getBanners()` method of searchResultQuery object can be used to fetch all banners related to that search. In case of a search we need to provide do we want banners for quicksearch or search landing page. In case of merchandising banners we do not need to provide anything for the method.

```javascript
const resultObject = await KlevuFetch(
    search(searchTerm, {
        // not required as for default it's the same.
        id: "search", 
    })
);

const banners = resultObject.queriesById("search").getBanners({ searchType: "quicksearch" })

```

## Get redirects related to search

`getRedirects` method of searchResultQuery will be defined in case that typical search was made. It will return all directs that are matched (usually one) to the search. This allows you to create your own redirection logic.

Here is very simple logic that you can use to do the redirects in the browser.

```javascript
const resultObject = await KlevuFetch(
    search(searchTerm, {
        // not required as for default it's the same.
        id: "search", 
    })
);

const redirects = resultObject.queriesById("search").getRedirect?.()
if (redirects && redirects[0]) {
  window.location.href = redirects[0].url
}

```

## Click Events

When you perform a search using KlevuFetch, each query can be accessed using getQueriesById as shown above.&#x20;

:::CodeblockTabs
React

```javascript
<Grid item key={i}>
    <Product
    product={p}
    onClick={() => {
        searchResult.searchClickEvent({
          productId: p.id
        })
    }}
    />
</Grid>
```

Vue

```javascript
<Product
    v-for="product in searchStore.products"
    :key="product.id"
    :product="product"
    @click="searchResult.searchClickEvent({
      productId: p.id
    })"
/>
```
:::

There are three possible click events returned by `getQueriesById()`: `searchClickEvent()`, `categoryMerchandisingClickEvent()` and `recommendationClickEvent()`

These three functions are defined and available only if query has been correct type. So for example `search()` query has only `searchClickEvent()` defined.&#x20;

| Function Name                       | Returned by             |
| ----------------------------------- | ----------------------- |
| `searchClickEvent()`                | search()                |
| `categoryMerchandisingClickEvent()` | categoryMerchandising() |
| `recommendationClickEvent()`        | kmcRecommendation()     |

For exact information regarding what is returned by searches and what to pass to these search events please refer to the [Reference](docId:6WnQmEACtqt_Z3sacZlW_) section.&#x20;

[title] Data Protection
[path] Guide/

By default, data protection is turned off in the SDK. This means that the SDK will read and write from the browser's storage (localStorage, cookies, etc).&#x20;

For customers who need to comply with data protection rules, you can enable data protection in the SDK by setting **useConsent** to **true**. When this setting is enabled, consent must be given for each session using the SDK using **consentGiven** with a value set to **true**.&#x20;

You can use the following code snippet as an example to enable it:

```javascript
KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  useConsent: true, //Either set it to true during initialization
  consentGiven: true, //Either set it to true during initialization
})
// or
KlevuConfig.getDefault().setUseConsent(true)
KlevuConfig.getDefault().setConsentGiven(true) // When you receive the user consent
```

You can either add values per user session within KlevuConfig.init or by calling the methods available to KlevuConfig as shown above.&#x20;

[title] Klevu Merchant Center Settings
[path] Guide/

[Klevu Merchant Center (KMC)](https://box.klevu.com) is a back office admin panel where users can change the settings of the Klevu products. Most of the settings are automatically applied in the API queries but some settings are at the level of UI development. For example, getting the keywords that are used for redirecting or personalized messages when there are no search results.

SDK doesn't automatically fetch this information or have any automatic business logic based on these settings. You as the developer have the responsibility to create the logic for your UI layer. More help on the data models and implementation details can be found from [API documentation](https://docs.klevu.com/apis/dashboard-settings).

But there is a helper you can use to fetch these settings. It can be used in any place of your code and it will cache response for visiting user for 24 hours.

```javascript
import { KlevuKMCSettings } from "@klevu/core";

async function somewhereInYourCode() {
  const settings = await KlevuKMCSettings();
}
```


[title] Request caching
[path] Guide/

Klevu SDK automatically caches sent request to local memory for speedier results for same requests.

If you a system where same KlevuFetch is called multiple times, for example when focusing on input, it is much more convinient to get results from local memory than making same request to Klevu API again and again.&#x20;

This happens automatically without any configuration with 10 minutes cache. If you wish disable or change the time of caching you change this with KlevuConfig in your initialization.

:::CodeblockTabs
```javascript
import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
  cacheMaxTTL: 10000 // 10 seconds memory cache. 
})
```

```typescript
import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
  cacheMaxTTL: 10000 // 10 seconds memory cache. 
})
```
:::

Cache is cleared if user browser make a full page navigation. In typical Single Page Application this cache is *not cleared* when changing route.


[title] Quickstart
[path] /

These instructions work with any javascript environment or framework that supports installing packages through NPM.

## Installation

First install required packages to your project with npm or yarn.

```shell
npm install @klevu/core
```

## Initialization

Before making any request it is required to provide the Klevu API key and the search server you are targeting. This should be done in the index of the application or the initialization of your app.

URL and apikey can be found from your KMC installation.

:::CodeblockTabs
```typescript
import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
})
```

```javascript
import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
})
```
:::

## Making a search

All queries to Klevu are made with **KlevuFetch** function. Inside KlevuFetch you provide any amount of query functions as parameters. In this example we do most basic product search with search term "*hoodies*".

:::CodeblockTabs
```typescript
import { KlevuFetch, search } from "@klevu/core"

const result = await KlevuFetch(search("hoodies"))
console.log(result.queriesById("search")?.records)
```

```javascript
import { KlevuFetch, search } from "@klevu/core"

const result = await KlevuFetch(search("hoodies"))
console.log(result.getQueriesById("search")?.records)
```
:::

## Simple Playground

[Click here](https://codesandbox.io/s/klevu-headless-sdk-hello-world-dupbtv?file=/src/index.ts) to see a simple example you can play with.




[title] Introduction
[path] /

With Klevu’s SDK library, you can pull the power of AI product discovery into any JavaScript ecosystem. It simplifies development giving you more time for innovation. Our SDK brings you the data from search, smart categories and recommendations as JSON. Then you can decide how to render this information.&#x20;

Another important part it does for you is analytical data sending. Making sure that everything is correct for Klevu AI to improve results. But it doesn't end just there. Our SDK library also provides you with helpers to manage filters, cache requests, simplifying pagination, etc

This library has been built for all browser based frameworks and the Node.js environment. This means that the library is agnostic and is available to use with most of the JavaScript libraries in both traditional and headless implementations.&#x20;

# What is headless

In headless you decouple the back-end systems from the presentation or display layer i.e. frontend. Simply to say, this CMS does have a front-end layer and only the back-end is there.&#x20;

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/bMQnp2REfZqkznwLRbjJV_traditional-webapp.jpg" size="58" width="1536" height="799" position="center" showCaption="false"}

Traditional web applications combine the frontend with the back-end, so when a user requests a page, the browser makes the request, the web server then requests data from the data base, processes the data, adds the data to a page template, then sends the entire page back to the browser. This leads to a complete unloading of the previous page (blank screen) and reloading of the new page. During the reloading of the new page, common elements such as fancy navigations must be reloaded and activated. The entire process takes time and is especially noticable on mobile devices with slower internet connections.&#x20;

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/OF9CHJViZOh5VpO-egQ3k_headless-webapp.jpg" size="54" width="1536" height="799" position="center" showCaption="false"}

With a headless web application, the back-end and frontend are separated. The back-end exposes an API to connect to the content, while the frontend makes requests to the API and then loads the content into the page dynamically. This method although a little more complex, provides huge performance gains by only needing to partially load portions of site that are actually changing from one page request to another. In other words, the fancy navigation we mentioned previously only needs to load once. And the partially loaded portions of the page only need to request the data which is much smaller than having to also load the code necessary to display the data.&#x20;

Performance is only one benefit to going headless. As previously mentioned, going headless also allows for a new level of freedom when it comes to the display of multiple data-sources which are very typical with traditional web applications. This limitation by traditional web applications is understandable. Each website is unique, like a fingerprint, and each website's requirements are also unique. Trying to make a website builder that supports every possible combination of data-sources is imposible to manage so traditional websites can only support a limited number of integrations with 3rd parties.&#x20;

With headless you have the freedom to build your website the way you want and there are many frontend frameworks out there with amazing features to make it possible.

# Integrate Klevu into your application with ease. We do all the heavy lifting.

Klevu SDK brings smart search, category merchandising and recommendations solution to your ecommerce store. Klevu makes it easy to create the best product browsing experience for your customers.

Klevu already has a simple to implement JavaScript library that is perfect for most users, so who is this library good for?

## TypeScript SDK

The Klevu SDK is written in TypeScript which gives you:

- Full auto-completion support of integrated development environments (IDEs)
- Full documenation from the code comments!
- Easy and fast way to integrate Klevu to your custom UI

## Open Source

The Klevu SDK is an open-source project, meaning that anyone can openly view the source code of [the project on GitHub](https://github.com/klevultd/frontend-sdk) to fully understand exactly what each line of code is doing. You can also contribute to the project if you have ideas on how to improve the project.&#x20;

The code on GitHub not only includes the SDK itself, but contains many examples built using many of the most popular frameworks such as React, Vue, Remix (React), NuxtJS 3 (Vue), and Vanilla JavaScript in case you don't want to deal with any framework at all.&#x20;

## SPA (Single Page Applications)

This library supports all the major frontend libraries like React and Vue. This SDK however gives you the ability to plugin Klevu smart search, category merchandizing and recommendations any way that you would like. Including event tracking of product clicks, searches, and purchases that drive the AI at Klevu's core.

## SSR & SSG (Server Side Rendering & Static Site Generation)

SSR & SSG are quickly becoming standard features in all of the most popular frontend frameworks such as NextJS and NuxtJS. With the Klevu SDK you can both increase your store's SEO and your user's experience by requesting search results, category pages, and recommendations before the page loads.

## PWA (Progressive Web Applications)

PWAs are designed to give users an experience on par with native apps. With the Klevu SDK, you can also bring the power of Klevu AI into your PWA.

## Full Creative Control, on Full Power

The Klevu SDK gives developers maximum control over the way they want to display and allow users to interact with your product catalog. When you add the SDK library to your project you have all the building blocks necessary to create trully unique user experiences that perfectly fit your brand.


[title] Query Functions
[path] Guide/

Query functions are basic building blocks of requests to Klevu backend. Any amount of them can be placed inside a **KlevuFetch&#x20;**&#x66;unction as parameters. It is recommended to use multiple query functions inside KlevuFetch instead of multiple KlevuFetch functions.&#x20;

Here is list of query functions available. Full listing with code reference can be found from @klevu/core reference.

| Klevu Function               | Description                                                                      | Type           |
| ---------------------------- | -------------------------------------------------------------------------------- | -------------- |
| `search()`                   | Most basic query to find items based on a term                                   | Search         |
| `suggestions()`              | Fetches suggestions based on a term.                                             | Search         |
| `trendingProducts()`         | Find all products that are trending right now in results                         | Search         |
| `categoryMerchandising()`    | Products to display on category page                                             | Search         |
| `searchCategory()`           | Search categories based on term                                                  | Search         |
| `searchCms()`                | Search CMS pages based on term                                                   | Search         |
| `products()`                 | Fetches products by id from Klevu                                                | Search         |
| `raw()`                      | Write raw request to Klevu api. For expert use                                   | Search         |
| `recentlyViewedProducts()`   | List of products user has recently viewed                                        | Search         |
|                              |                                                                                  |                |
| `kmcRecommendation()`        | Fetches predefined recommendation by id from KMC and creates query automatically | Recommendation |
| `newArrivals()`              | Recommendation list of new arrivals for the current user                         | Recommendation |
| `trendingCategoryProducts()` | Trending recommendation based for current user                                   | Recommendation |
| `similarProducts()`          | Fetch similar products based on given ids                                        | Recommendation |
| `alsoViewed()`               | Product recommendations what user should also check out                          | Recommendation |
| `boughTogether()`            | On checkout page check what products are recommended to current cart products    | Recommendation |


[title] Vue Examples
[path] Examples/

## Vue 3 Examples

Vue is an approachable, performant and versatile framework for building web user interfaces. We built an example using the latest version at the time of creating the Klevu Headless SDK, Vue 3, to show how one could use the Klevu Headless SDK in a real-world application.

Click here to see how we built our Vue 3 example: [Code](https://github.com/klevultd/frontend-sdk/tree/master/examples/vue)

## NuxtJS 3 Examples

NuxtJS is a Hybrid Vue Framework for building applications with Vue 3 and experience hybrid rendering, powerful data fetching and new features. Nuxt 3 is an open source framework making web development simple and powerful.

For example, NuxtJS provides SSR (server side rendering) which provides better SEO by prerendering the HTML on the server before sending it to the browser.&#x20;

Click here to see how we built our NuxtJS 3 example: [Code](https://github.com/klevultd/frontend-sdk/tree/master/examples/nuxt3)


[title] Contributions, requests & issues
[path] /

Klevu Headless SDK is hosted in [GitHub](https://github.com/klevultd/frontend-sdk). You can checkout the code, test and run example and create changes.&#x20;

To run the example you need to checkout the code, build and run it. You should have example running in [http://localhost:3001](http://localhost:3001)

```shell
# Checkout the code
git checkout https://github.com/klevultd/frontend-sdk.git

# go in the folder
cd frontend-sdk

# build project
npm run build

# run example
npm run example
```

## Contributing

You are welcome to fork the project, make changes and then create a pull request to it. Your changes will go through standard testing and review process where we might request changes to your code. For style of the code we are using `eslint `to check the styling. You can easily check the code by running `npm run qoc`.

## Requests

For feature request we are using GitHub's issue tab. Just create new issue with **enchanment** label. Then there will be discussion around the request. When it's taken to backlog it will receive a milestone in GitHub.&#x20;

## Issues

Issues work in the same way as requests. Just create new issue in the GitHub and choose good label for it. For direct support you can visit [Help Center](https://support.klevu.com) or send us email to [support@klevu.com](mailto\:support@klevu.com).


[title] JavaScript (vanilla) Examples
[path] Examples/

## JavaScript Examples

This very simple example shows you how to make a search request and how to output the results as a JSON object into the page.

Click here to view our JavaScript example: [Code](https://github.com/klevultd/frontend-sdk/tree/master/examples/vanillajs)




[title] Examples
[path] /

To help you get started as quickly as possible in implementing Klevu in your new or existing project, we've created a number of examples using some of the most powerful and popular frameworks.

We've included the code for all our examples in the [GitHub](https://github.com/klevultd/frontend-sdk) repo for the Klevu Headless SDK.&#x20;

- [JavaScript (vanilla) Examples](docId\:TxO08IsxNCybiHwWXTHbQ)&#x20;
- [React Examples](docId\:nh7dn6mx9yUONIRYT5X51)&#x20;
- [Vue Examples](docId\:nGClzNqesHP6-fAeo9OYT)&#x20;


[title] React Examples
[path] Examples/

## ReactJS Examples

This is our most feature rich example to highlight many of the features available in the Klevu Headless SDK.

Click here to view our ReactJS Example: [Live Demo](https://headlessdemo.klevu.com/) | [Code](https://github.com/klevultd/frontend-sdk/tree/master/examples/react)

To help better understand how to implement the Klevu Headless SDK into your new or existing React project we've organized the features into a table with links to the source code where they are implemented.&#x20;

### Search

| Feature                     | Description                                                           | Link to Example                                                                                                             |
| --------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Quick Search                | Example used to display search results as you type into a text field. | [quicksearch.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/components/quicksearch.tsx)       |
| Search Results Landing Page | Example to show search results based on a keyword passed in the URL.  | [SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx) |
| Category Navigation         | Example display of products in a Category/Collection.                 | [CategoryPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/CategoryPage.tsx)         |
| Single Product Search       | Example of using search to query the data for a single product.       | [ProductPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/ProductPage.tsx)           |
| Filters                     | Examples of filters to narrow down products based on product facets.  | [SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx) |
| Load More Results           | Example of a Load More button to request more products.               | [SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx) |

### Analytics

Analytics drive the Machine Learning Klevu uses to provide users the best results. It is important to track key user interactions and send this data to Klevu. Here are examples of how easy it is to implement using the Klevu Headless SDK.&#x20;

| Feature                                 | Description                                              | Link to Example                                                                                                             |
| --------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| SearchEvent                             | Track what was searched.                                 | [SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx) |
| Search Product Click Event              | Track the products that are clicked from search results. | [SearchResultPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/SearchResultPage.tsx) |
| Category Navigation Product Click Event | Track the products that are clicked from category pages. | [CategoryPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/CategoryPage.tsx)         |
| Buy/Purchase Event                      | Track the products that are purchased.                   | [CheckoutPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/CheckoutPage.tsx)         |

### Recommendations

| Feature                               | Description                                    | Link to Example                                                                                                   |
| ------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Klevu Merchant Center Recommendations | Add recommendations created within KMC.        | [HomePage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/HomePage.tsx)       |
| Similar Products                      | Request similar products based on a product ID | [ProductPage.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/routes/ProductPage.tsx) |

### Utilities

| Feature          | Description                                                               | Link to Example                                                                                |
| ---------------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| KlevuKMCSettings | Load your Klevu Merchant Center settings into the browser's localstorage. | [index.tsx](https://github.com/klevultd/frontend-sdk/blob/master/examples/react/src/index.tsx) |



## RemixJS Examples

Remix is a full stack web framework that lets you focus on the user interface and work back through web standards to deliver a fast, slick, and resilient user experience.

Remix is a seamless server and browser runtime that provides snappy page loads and instant transitions by leveraging distributed systems and native browser features instead of clunky static builds. Built on the Web Fetch API (instead of Node) it can run anywhere. It already runs natively on Cloudflare Workers, and of course supports serverless and traditional Node.js environments, so you can come as you are.

In this example, we leverage the power of Server-Side Rendering and the Klevu Headless SDK to generate a complete ecommerce site.&#x20;

Click here to view our RemixJS Example: [Code](https://github.com/klevultd/frontend-sdk/tree/master/examples/remix)


[space] Data Indexing (/indexing-apis)

[title] Rate Limits
[path] JSON API/

## API Rate Limits

Klevu's API ecosystem is designed to facilitate efficient communication and robust operations, making it an integral part of our product discovery suite. To maintain optimal performance and ensure stability, rate limits are applied to manage the volume of requests.

## Overview of Rate Limits

Klevu uses a Web Application Firewall (WAF) to enforce rate limits. This system monitors incoming requests and applies restrictions when the defined thresholds are exceeded. These limits are particularly relevant for managing data ingestion into the Klevu backend, where processing times may vary based on payload size and complexity.

### Key Specifications

- **Request Limit**: 200 requests per minute.
- **Scope**: Applies to all indexing-related APIs, including PUT, PATCH, and attribute fetch endpoints.
- **Payload Size**: Each request must adhere to Klevu's **2 MB payload size limit** to ensure efficient processing and avoid rejection.

### Response When Limit Is Exceeded

If the request volume surpasses the allowed limit, the API will return:

- **HTTP Status Code**: 429 (Too Many Requests)
- **Message**: "Rate Limit Exceeded"

:::hint{type="warning"}
In such cases where limits are exceeded, additional requests must be paused until the rate resets.
:::



## Recommendations for Effective API Usage

To make the most of Klevu's API capabilities while staying within the rate limits, consider these best practices:

### Batch Operations

Whenever possible, consolidate multiple operations into a single request. This reduces the overall number of API calls and optimizes resource usage, ensuring efficient catalog management.

### Optimize Payload Size

Ensure that each request complies with the **2 MB payload size limit**. Oversized payloads may experience delays or rejection, impacting integration performance.

### Account for Processing Variability

The time required to process requests depends on their size and complexity. Design your integration workflows to handle variable processing times by incorporating delays or retries where necessary.






[title] Settings
[path] JSON API/

The Settings API is designed to allow developers to configure default settings for the Klevu indexing system before sending data updates. This pre-configuration step ensures that certain parameters, such as default currency, are set and consistently applied to all subsequent data updates. As Klevu continues to evolve, more configurable settings will be added to enhance the indexing system's capabilities and enable it to make decisions based on these configurations.

**Setting Default Currency**

:::hint{type="info"}
If no default currency is set, our backend service will automatically use the currency found in the first record of the first batch submitted as the default currency.
:::



To ensure that all product prices are indexed in the default currency of USD. By configuring this setting upfront, they can avoid inconsistencies in currency handling across different data updates.

:::ApiMethodV2
```json
{
  "name": "showcasing how to set default currency ",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/settings",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "curl",
        "code": "curl --location --request PUT 'https://indexing-api.ksearchnet.com/v2/settings' \\\n--header 'X-KLEVU-AUTH-ALGO: HmacSHA384' \\\n--header 'X-KLEVU-TIMESTAMP: 2023-07-10T08:38:00Z' \\\n--header 'X-KLEVU-APIKEY: klevu-1592574318858490' \\\n--header 'Content-Type: application/json' \\\n--header 'Authorization: Bearer YQVmPq63wosB760EAkUNdomeI3Rlm+EFKdg7weXnIFewCCD6eJQJJ5h/w/HdtFpG' \\\n--data '{\"defaultCurrency\":\"GBP\"}'",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"message\": \"Store settings updated.\"\n}"
      },
      {
        "id": "MOb-nxb4iBJs_9a-FK9gU",
        "language": "400",
        "code": "{\n  \"status\": 400,\n  \"code\": \"VALIDATION_ERROR\",\n  \"message\": \"The request was invalid. Please check the provided payload for errors.\",\n  \"debug\": [\n    {\n      \"message\": \"The attribute defaultCurrency has an invalid currency code 'SOO'. It must be a valid code according to ISO 4217 standards.\"\n    }\n  ]\n}",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      },
      {
        "name": "Authorization",
        "kind": "required",
        "type": "string",
        "description": "This is the generated security token that authenticates the request.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "hasTryItOut": false,
  "autoGeneratedAnchorSlug": "showcasing-how-to-set-default-currency",
  "legacyHash": "hPcV-w96SdS5Osxv_jYo3"
}
```
:::


[title] Customer Groups
[path] JSON API/Examples/Batch Updates/

If you support various customer groups for your e-commerce website and want to maintain different prices for them, you can do it using the "groups" attribute. Following is an example where group prices are added for “grp\_1” and “grp\_2”. To understand how to use them at Storefront API, please refer:: [https://docs.klevu.com/apis/smart-search-examples#GI08Z](https://docs.klevu.com/apis/smart-search-examples#GI08Z)

## Group name Validations:

- It may consist of alphanumeric characters (letters and numbers) and underscores (`_`).
- Consecutive underscores (`__`) are not allowed.
- The group name must not be solely composed of underscores (`_`).

here are examples group names can be Sales\_Team, Marketing123, customer\_group

Example:

:::BlockQuote
\[
&#x20; \{
&#x20;   "id": "1",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 1" }
&#x20;     }
&#x20;   "groups": \{
&#x20;           "grp\_1": \{
&#x20;               "attributes": \{
&#x20;                   "price": \{
&#x20;                       "GBP": \{
&#x20;                           "salePrice": 10.0,
&#x20;                           "defaultPrice": 11.0
&#x20;                       }
&#x20;                   }
&#x20;               }
&#x20;           },
&#x20;           "grp\_2": \{
&#x20;               "attributes": \{
&#x20;                   "price": \{
&#x20;                       "GBP": \{
&#x20;                           "salePrice": 20.0,
&#x20;                           "defaultPrice": 21.0
&#x20;                       }
&#x20;                   }
&#x20;               }
&#x20;           }
&#x20;     }
&#x20; }
]
:::


[title] Partial Updates (Patch)
[path] JSON API/

### Overview

The PATCH API allows for partial updates of records within the Klevu indexing system. This means that you can update specific fields of a record without needing to resend the entire record. This is particularly useful for making quick, incremental updates to your data, reducing bandwidth usage, and improving efficiency. The PATCH API adheres to the JSON PATCH (RFC 6902) standard, ensuring a flexible and standardized approach to partial updates.

### Use Cases

1. **Price Updates**: A retailer wants to update the prices of products frequently based on market trends or promotional events. Using the PATCH API, they can update the price attribute without resending the entire product record.
2. **Stock Level Adjustments**: An online store needs to update the stock levels of products as sales occur. The PATCH API allows them to adjust the stock attribute efficiently.
3. **Metadata Updates**: A content management system (CMS) needs to update metadata like tags or descriptions of articles without altering the core content. Using the PATCH API, they can target these specific attributes.

### Limitations

- **Immutable Fields**: The `id` and `type` attributes cannot be changed. Any attempt to modify these fields will result in an error.
- **JSON PATCH Operations**: The API only supports operations defined by JSON PATCH (RFC 6902) such as `add`, `remove`, `replace`



:::hint{type="info"}
For more detailed information on API specifications, we recommend referring data indexing API definition on the Swagger online editor, please click the [link](https://editor.swagger.io/?url=https://klevu-public-files.s3.eu-west-1.amazonaws.com/publish/klevu-indexing-p1.yaml)
:::

### Examples of partial updates

please refer to the examples available [Relations](docId\:FN6LnecBXrBLOZ6HPhaKz)

[title] Untitled
[path] JSON API/Examples/


[title] Untitled
[path] JSON API/Examples/


[title] Changelogs
[path] JSON API/

:::Changelog{title="7 November 2024 -  Infrastructure upgrade and domain change "}
::ChangelogItem{type="improved" description="Upgraded Infrastructure and introduced a new domain : indexing-api.ksearchnet.com"}
:::

:::Changelog{title="9 October 2024 -  Fix for job tracking end-point"}
::ChangelogItem{type="fixed" description="Implemented a fix for identifying race conditions in job tracking and for marking jobs as completed."}
:::

:::Changelog{title="11 September 2024 -  Attributes alias support"}
::ChangelogItem{type="added" description="Added support attribute alias support for attribute validations. "}
:::

:::Changelog{title="15th August 2024 -  Validations and account expiry"}
::ChangelogItem{type="added" description="Added validation to reject XML indexing version and account expiry."}
:::

:::Changelog{title="13th August 2024 -  API performance improvement "}
::ChangelogItem{type="improved" description="Backend optimisation to improve API performance significantly. "}
:::

:::Changelog{title="13th August 2024 -  API performance improvement "}
::ChangelogItem{type="improved" description="Backend optimisation to improve API performance significantly. "}
:::

:::Changelog{title="7th August 2024 -  Bug fix related jobs getting dropped "}
::ChangelogItem{type="broken" description="Fixed a bug related to jobs not getting completed. "}
:::

:::Changelog{title="23 July 2024 -  Bug fix related to replication"}
::ChangelogItem{type="broken" description="Fixed a bug related to replication when freeze & unfreeze options are used. "}
:::

:::Changelog{title="19 July 2024 -  Improved logging"}
::ChangelogItem{type="improved" description="Improved logging for backend services. "}
:::

:::Changelog{title="18 July 2024 -  Bug fix related to product relation"}
::ChangelogItem{type="broken" description="Fixed issue related records missing KLEVU_PARENT_PRODUCT."}
:::

:::Changelog{title="17 July 2024 -  Bug fix for jobs experiencing failures"}
::ChangelogItem{type="broken" description="Fixed an issue causing failures in certain job processes."}
:::

:::Changelog{title="15 July 2024 -  Job tracker and freeze/unfreeze index support"}
::ChangelogItem{type="added" description="Released a feature to track submitted data updates using job-tracking APIs."}

::ChangelogItem{type="added" description="Released a feature to freeze and unfreeze the index, more information can be requested by submitting a support ticket."}
:::

:::Changelog{title="3 July 2024 -  Category inheritance"}
::ChangelogItem{type="fixed" description="Fixed the issue where category information was inherited from the parent despite the variant being linked to a different category."}
:::

:::Changelog{title="27 June 2024 -  Cascading updates"}
::ChangelogItem{type="fixed" description="Fixed the issue with cascading updates not working when updating variant prices."}
:::

:::Changelog{title="25 June 2024 -  Backend version upgrade"}
::ChangelogItem{type="added" description="Upgraded internal backend application version."}
:::

:::Changelog{title="24 June 2024 -  Default currency and allowed domain check"}
::ChangelogItem{type="improved" description="Enhanced the process of obtaining the default currency when not explicitly defined."}

::ChangelogItem{type="added" description="Implemented support for validating domain checks on batch updates."}
:::

:::Changelog{title="17 June 2024 -  Support for images in CMS pages and range filters"}
::ChangelogItem{type="added" description="Introduced the feature to submit images as part of CMS data."}

::ChangelogItem{type="added" description="Introduced option to select attributes as a range filter when registering the attribute definitions. "}
:::

:::Changelog{title="14 May 2024 -  Indexing performance improvements"}
::ChangelogItem{type="improved" description="Implemented major changes to optimize access patterns in backend services."}
:::

:::Changelog{title="10 May 2024 - Autosuggestions for records"}
::ChangelogItem{type="knownIssue" description="Resolved the issue causing automatic generation of product autosuggestions."}
:::

:::Changelog{title="6 May 2024 - Indexing performance improvements"}
::ChangelogItem{type="improved" description="Performed major optimizations to significantly improve the speed of indexing updates."}
:::

:::Changelog{title="2 April 2024 - Improvements related to dedupe, default stock status"}
::ChangelogItem{type="added" description="By default, all record types are marked in stock. "}

::ChangelogItem{type="improved" description="Implemented a hashing component to prevent duplicate indexing of updates."}
:::

:::Changelog{title="18 March 2024 - Validations and support for boosting"}
::ChangelogItem{type="added" description="Implemented validation for indexing versions and introduced support for manually submitting product boosting scores when sending data updates."}
:::

:::Changelog{title="7 March 2024 - Enhanced memory management for backend services"}
::ChangelogItem{type="improved" description="Improvements related to memory allocations."}
:::

:::Changelog{title="5 March 2024 - Bug fixes & improvements "}
::ChangelogItem{type="knownIssue" description="Fixes and improvements to handle internal application communications"}
:::

:::Changelog{title="4 March 2024 - Application monitoring"}
::ChangelogItem{type="improved" description="Introduced detailed metrics for backend applications monitoring and data updates. "}
:::

:::Changelog{title="19 February 2024 - Performance improvements"}
::ChangelogItem{type="improved" description="Backend optimizations to significantly accelerate the speed of data update indexing."}
:::

:::Changelog{title="12 February 2024 - Major backend restructuring and support for new features"}
::ChangelogItem{type="added" description="Support for cascading."}

::ChangelogItem{type="fixed" description="Intermittent backend service failures."}

::ChangelogItem{type="improved" description="Backend services optimizations, Streamlined error codes, Documentation, Restructuring of swatches."}
:::

:::Changelog{title="7 November 2023 - Bug Fixes and support for new features"}
::ChangelogItem{type="added" description="Support for display property and visibility for products. "}

::ChangelogItem{type="fixed" description="Indexing of category data, Support for multivalued string."}

::ChangelogItem{type="improved" description="Streamlined responses."}
:::

:::Changelog{title="11 August 2023 - Alpha Release"}
::ChangelogItem{type="added" description="We are excited to announce the initial release of our API, bringing you powerful new features to enhance your development experience. This release includes support for JSON indexing, schema management, and authentication, providing a robust foundation for your applications. Dive into the documentation to explore how these features can streamline your workflow and improve efficiency."}
:::


[title] Untitled
[path] /


[title] Custom Attributes
[path] JSON API/Examples/Batch Updates/

In the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8), you will find that we have some predefined attributes for the item. That will not suffice all the use cases, e.g. you have brand, color, size, etc fields for your product.

Before indexing the additional attributes, the attribute definition needs to be created. Details of various options are available in the API Schema.

:::ApiMethodV2
```json
{
  "name": "Add custom attribute: brand",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/brand",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "json",
        "code": "{\n  \"label\": {\n    \"default\": \"Brand Label\"\n  },\n  \"searchable\": true,\n  \"filterable\": true,\n  \"returnable\": true,\n  \"datatype\": \"STRING\"\n}\n",
        "customLabel": "Request Body (JSON)"
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n      \"message\": \"Attribute saved successfully.\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-custom-attribute-brand",
  "legacyHash": "KizitdZDHFQ2TWWLGBzzf"
}
```
:::

:::ApiMethodV2
```json
{
  "name": "Add custom attribute: size",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/size",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "json",
        "code": "{\n  \"label\": {\n    \"default\": \"Size Label\"\n  },\n  \"searchable\": true,\n  \"filterable\": true,\n  \"returnable\": true,\n  \"datatype\": \"STRING\"\n}",
        "customLabel": "Request Body (JSON)"
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n     \"message\": \"Attribute saved successfully.\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-custom-attribute-size",
  "legacyHash": "XZyCEKc_Ly6PLZ2IsSk93"
}
```
:::

The above API has created two attributes, brand and size. Important to note that the attribute key should be sanitized, without any special characters. This needs to be done only once, not every time you index products. For more information on the supported data types, please refer to the [Data Types](docId\:Ib9Ci4fOeIfFefORoxofO).

Once the attribute definition is created, let's index the product.

:::BlockQuote
\[
&#x20; \{
&#x20;   "id": "1",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 1" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "s"
&#x20;   }
&#x20; },
&#x20; \{
&#x20;   "id": "2",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 2" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "m"
&#x20;   }
&#x20; }
]
:::

In the above example, we have indexed the two new attributes to the product, i.e. brand and size.

### Example for MULTIVALUE attribute registration

:::ApiMethodV2
```json
{
  "name": "Add custom attribute: materials",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/materials",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "curl",
        "code": "curl --location --request PUT 'https://indexing-api.ksearchnet.com/v2/attributes/custom1' \\\n--header 'X-KLEVU-AUTH-ALGO: HmacSHA384' \\\n--header 'X-KLEVU-TIMESTAMP: 2023-07-10T08:38:00Z' \\\n--header 'X-KLEVU-APIKEY: klevu-1592574318858490' \\\n--header 'Content-Type: application/json' \\\n--header 'Authorization: Bearer YQVmPq63wosB760EAkUNdomeI3Rlm+EFKdg7weXnIFewCCD6eJQJJ5h/w/HdtFpG' \\\n--data '{\n    \"label\": {\n        \"default\": \"Materials\"\n    },\n    \"searchable\": true,\n    \"filterable\": false,\n    \"returnable\": false,\n    \"datatype\": \"MULTIVALUE\"\n}'",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n      \"message\": \"Attribute saved successfully.\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      },
      {
        "name": "Authorization",
        "kind": "required",
        "type": "string",
        "description": "This is the generated security token that authenticates the request.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-custom-attribute-materials",
  "legacyHash": "p0coOo0_ENySJVrb1X2eh"
}
```
:::

### A sample batch request

:::BlockQuote
\[
&#x20;   \{
&#x20;       "id": "1",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Product 1"
&#x20;           },
&#x20;           "brand": "UCB",
&#x20;           "materials": \[
&#x20;               "20% cotton",
&#x20;               "80% polyester"
&#x20;           ]
&#x20;       }
&#x20;   }
]
:::

## Abbreviate

The abbreviations feature allows you to automatically generate shortened forms of values for searchable attributes. This can be useful for improving search relevance and efficiency.

:::hint{type="info"}
By default, the attributes with key "brand" and "manufacturer are abbreviated to enhance search and retrieval efficiency.
:::



The abbreviation logic follows these steps:

1. **Initials Generation**: Each word in the submitted data is abbreviated to its initials.
   - Example: "Larsen & Toubro" becomes "L\&T".
2. **Handling Special Characters**: Special characters like "&" are replaced with no space.
   - Example: "Larsen & Toubro" becomes "LT".

For a given value "Larsen & Toubro", the abbreviations generated are:

- **L\&T**

  : Using initials with special characters preserved.
- **LT**

  : After replacing special characters.

**Example**

:::ApiMethodV2
```json
{
  "name": "Add custom attribute: vendor",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/vendor",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "json",
        "code": "{\n  \"label\": {\n    \"default\": \"Brand Label\"\n  },\n  \"searchable\": true,\n  \"filterable\": true,\n  \"returnable\": true,\n  \"abbreviate\": true,\n  \"datatype\": \"STRING\"\n}\n",
        "customLabel": "Request Body (JSON)"
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n      \"message\": \"Attribute saved successfully.\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-custom-attribute-vendor",
  "legacyHash": "b8J90NqUgq4bhI-dxoH7A"
}
```
:::

## Rangeable

This property enhances search flexibility by allowing users to filter data based on numeric ranges, optimizing search and retrieval operations. It only works with the attributes that are registered as NUMBER or MULTIVALUE\_NUMBER as a data type.

**Example**

:::ApiMethodV2
```json
{
  "name": "Add custom attribute: length",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/length",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "json",
        "code": "{\n  \"label\": {\n    \"default\": \"Brand Label\"\n  },\n  \"searchable\": true,\n  \"filterable\": true,\n  \"returnable\": true,\n  \"rangeable\": true,\n  \"datatype\": \"NUMBER\"\n}\n",
        "customLabel": "Request Body (JSON)"
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n      \"message\": \"Attribute saved successfully.\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-custom-attribute-length",
  "legacyHash": "u9DLTNQWVOwfhp8FunRRu"
}
```
:::


[title] Data Types
[path] JSON API/

When registering attributes with our API, you can specify various data types to ensure proper handling and validation of the data. By understanding and utilizing these data types, you can ensure that your attributes are registered correctly, leading to better data management and retrieval. Here’s an overview of the attribute data types we support:

### STRING

Represents a sequence of characters. Use this data type for textual data.

### MULTIVALUE

Represents an array of strings. Use this data type for attributes that require multiple string values.

:::hint{type="info"}
- The [grouping](https://docs.klevu.com/apis/advanced-filtering) of a custom attribute doesn't work when selecting MULTIVALUE as the data type.&#x20;
:::

### NUMBER

Represents any decimal number ranging between -9999999999999 and 9999999999999.&#x20;

:::hint{type="info"}
- It supports up to 7 decimal points; beyond this, rounding may occur.
- Mantissa values (parts of a number in scientific notation) will be accepted but their behavior is not guaranteed.
- When selecting an attribute for use as a range filter, you must choose the **NUMBER** data type. For more information on how to implement [range filters](https://docs.klevu.com/apis/faceting).&#x20;
- To enable **NUMBER** for a range filter's min-max range, the attribute definition will need to be updated to include [rangeable\:true](https://docs.klevu.com/indexing-apis/custom-attributes#GFoTy).
:::

### MULTIVALUE\_NUMBER

Represents an array of numerical values (each following the NUMBER data type specifications). Use this data type for attributes that require multiple numerical values.

:::hint{type="info"}
- When using **MULITVALUE\_NUMBER** for a range filter's min-max range, the attribute definition will need to be updated to include [rangeable\:true](https://docs.klevu.com/indexing-apis/custom-attributes#GFoTy).
:::






[title] Attributes
[path] JSON API/Examples/Partial Updates (Patch)/

Patching specific attributes for a list of products.&#x20;

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "replace",
            "path": "/attributes",
            "value": {
                "name": {
                    "default": "Comfortable Chair ITEM001"
                },
                "price": {
                    "USD": {
                        "salePrice": 50.00,
                        "defaultPrice": 70.00,
                        "toPrice": 70.00,
                        "startPrice": 50.00
                    },
                    "GBP": {
                        "salePrice": 50.00
                    }
                }
            }
        }
    ],
    "ITEM002": [
        {
            "op": "replace",
            "path": "/attributes/name",
            "value": {
                "default": "Comfortable Chair ITEM002"
            }
        }
    ]
}
```
:::

Patching attribute with a specific locale for a given product

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "add",
            "path": "/attributes/description/default",
            "value": "Comfortable Chair ITEM001"
        },
        {
            "op": "add",
            "path": "/attributes/shortDescription/default",
            "value": "Comfortable Chair ITEM001"
        }
    ]
}
```
:::


[title] Introduction
[path] /

Klevu's Indexing API is a powerful tool that enables a wide range of operations on items within your store catalog. These items could be anything from products and categories to content pages or any other entity type that your specific business requires. This API is designed to streamline and enhance catalog management for e-commerce merchants, making it a valuable component of Klevu's product discovery suite.

Optionally, Klevu also provides support for [Data Feed.](https://help.klevu.com/support/solutions/articles/5000871297-feed-format)

[title] Authentication
[path] JSON API/

All calls to the indexing API are authenticated by signing the request using HMAC with SHA384 as the hash function. Your REST API key is used to calculate the signature. The signature must be calculated as described on this page.

# How to calculate the signature

To calculate a signature for your request implement the following algorithm in your application.

## Algorithm

Determine the following information about your request:

- HTTP method used, e.g. "**PUT**"
- URL path, e.g. "**/v2/batch**"
- Query string, e.g. "**test=1**"
- Secured headers, in order:
  - X-KLEVU-TIMESTAMP, e.g. "**2023-06-19T00:00:00.000Z**"
    - *⚠️ The timestamp validation window is set to 20 minutes. Timestamp values provided by the merchant will be considered valid if they fall within a range of 10 minutes in the past and 10 minutes in the future.*
  - X-KLEVU-APIKEY, e.g. **"klevu-1234567890"**
  - X-KLEVU-AUTH-ALGO, e.g. "**HmacSHA384**"
    - This must match exactly including case.
  - Content-Type, e.g. "**application/json**"
- Request body, e.g. "**\{}**"
  - This must be the exact request body that will be sent to the API.

Construct a string containing:

:::BlockQuote
\<Method>
\<URL path>
\<Query string>
\<Secured headers one per line, these are case sensitive>
\<Request body>
:::

For example, using the data from above:

:::BlockQuote
PUT
/v2/batch
test=1
X-KLEVU-TIMESTAMP=2023-06-19T00:00:00.000Z
X-KLEVU-APIKEY=klevu-1234567890
X-KLEVU-AUTH-ALGO=HmacSHA384
Content-Type=application/json
\{}
:::

In the previous example, note the case of the header keys as well as the data. The X-KLEVU- header keys are expected in upper case and "Content-Type" must match as well.

Calculate the binary signature bytes using the HMAC algorithm with SHA384 as the hash function. Use your REST API key as the secret:

:::BlockQuote
signaturebytes = Hmac(SHA384, constructedString, secret)
:::

Next base64 encode the byte to get your signature.

:::BlockQuote
signature = base64encode(signaturebytes)
:::

Set the Authorization header on your request to "Bearer \<signature>". Substitute the content of the signature variable in place of "\<signature>".

For this example, the full request would be:

:::BlockQuote
Request URL: https\://indexing-api.ksearchnet.com/v2/batch?test=1
Request Method: PUT

Headers:
X-KLEVU-TIMESTAMP=2023-06-19T00:00:00.000Z
X-KLEVU-APIKEY=klevu-1234567890
X-KLEVU-AUTH-ALGO=HmacSHA384
Content-Type=application/json

Request body:
\{}
:::

## Sample Postman Collection for HMAC Generation in Batch Requests

Included below is a sample Postman collection demonstrating the process of generating HMAC signatures for batch requests of records.

::File[]{src="https://archbee-doc-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/3xsnd9dpNR5KYKpQ83m_6_klevu-data-indexing-json-apis.json" label="Klevu_Data_Indexing_JSON_APIs.json"}

The above file comprises a sample batch request. Upon importing the collection, you'll find a pre-request script that dynamically generates a signature tailored to the submitted request. Within this batch request, a sample category record is included.

::File[]{src="https://archbee-doc-uploads.s3.amazonaws.com/mxGEHm-xWG9KnLLKKRd64-D-VezJDpgNM0lREjlU9sM-20241107-124331.json" label="Klevu_Data_Indexing_JSON_APIs_ENV.json"}

This file lists the environment variables necessary for signature generation. Upon import, we recommend updating the values for the following variables: **apiKey** and **restAuthKey** with your respective JS API Key and REST API Key. For guidance on obtaining API Keys, please refer to [this article](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-).

[title] JSON API
[path] /



Indexing API v2 brings in JSON support to index the products. Following are a few key concepts for the API:

1. **RESTful HTTP Approach:** The Indexing API is built on the principles of Representational State Transfer (REST). This means it leverages standard HTTP methods for communication. You can perform operations like adding, updating, or deleting catalog items, making integrating with your existing systems easy.
2. **Asynchronous and Batch Processing:** The API operates asynchronously and in batches. When you initiate changes to your catalog using the API, it creates a job for each action. The jobs are executed in asynchronous and distributed ways to achieve scale and performance. This job-based approach allows us to manage and optimize the processing of a large number of catalog updates efficiently.&#x20;
3. **Security Measures:&#x20;**&#x4B;levu's Indexing API prioritizes the security of catalog updates. To submit data, you must generate a token using your secret key. This two-step verification process ensures that only authorized users can change the catalog. It's a critical security measure to protect your valuable data.

In summary, Klevu's Indexing API offers a versatile and secure way to manage your store catalog, and it does so with a RESTful, asynchronous, and batch-oriented approach. By incorporating job monitoring and a stringent security process, it becomes a valuable asset for e-commerce merchants using Klevu's product discovery suite.

[title] Errors
[path] JSON API/

:::hint{type="warning"}
**Merchants are responsible for ensuring the accuracy of the data they submit. This includes checking for:**

- Leading and trailing spaces included in the submitted data are considered valid and are retained during processing in our backend.
- Special characters included in the submitted data are properly escaped to ensure compatibility with JSON format.
- HTML formatting in descriptions or short descriptions is correctly escaped to prevent unintended rendering issues.
- The startPrice and toPrice are calculated only when not explicitly submitted for all variants within a given complex product.
:::

At Klevu.com, we utilize conventional HTTP response codes to convey the outcome of API requests.&#x20;

- Responses in the **2xx** range signify successful operations.
- Responses in the **4xx** range denote errors stemming from the provided information, such as missing required parameters or failed requests.
- Responses in the **5xx** range signify issues with Klevu's servers, though these are uncommon.

```json
{
    "status": {{http_status_code}},
    "code": "{{error_code}}",
    "message": "{{human readable message}}",
    "debug": [
        {"id":"{{optional_document_id}}","message":"{{detailed message that helps to debug the error.}}"}
    ]
}
```

### Understanding the error response:

| **Parameters** | **Description**                                                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| status         | HTTP status codes: 400,401, 405, 413, 415, 500, 502, 503, 504                                                                                     |
| code           | The type of error returned. please see below reference table below for more information.                                                          |
| message        | A brief overview of the error.                                                                                                                    |
| debug          | A comprehensive breakdown of the error, highlighting the reason for the issue along with specific details regarding the record causing the error. |

### Error Message Illustrations:&#x20;

| **status**       | **code**                 | **message**                                                                       | **debug**                                                                                                                                                                                                                                                                                                                                     |
| ---------------- | ------------------------ | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 400              | VALIDATION\_ERROR        | The request was invalid. Please check the provided payload for errors.            |  \[  \{"id":"1233AD","message":"Attribute: brand is undefined."}&#xA;]                                                                                                                                                                                                                                                                        |
| 400              | INVALID\_REQUEST         | The request was invalid. Please check the provided payload for errors.            |  \[&#xA;   \{&#xA;            "message": "The store is currently configured to use XML Data Indexing APIs. Before you can begin using the new JSON endpoint, a backend migration is required. Please submit a support ticket at https\://help.klevu.com/support/tickets/new to request assistance with the backend migration process."}&#xA;] |
| 401              | AUTHENTICATION\_ERROR    | Authentication failed. Please ensure your credentials are valid and try again.    | \[\{"message":"The supplied credentials are invalid."}&#xA;]                                                                                                                                                                                                                                                                                  |
| 405              | METHOD\_NOT\_ALLOWED     | The request method is not allowed.                                                | \[ \{"message":"Please ensure you are using a valid request method for this endpoint. The allowed methods are GET/POST/DELETE."}&#xA;]                                                                                                                                                                                                        |
| 413              | CONTENT\_TOO\_LARGE      | The batch content in the request exceeds the allowable size limit for processing. | \[\{"message" : "The request content is too large. The maximum allowed size is 2MB."}]                                                                                                                                                                                                                                                        |
| 415              | UNSUPPORTED\_MEDIA\_TYPE | The request Content-Type is not allowed.                                          | \[ \{"message": "The request header Content-Type: text/plain is not supported for this endpoint."  }]                                                                                                                                                                                                                                         |
| 500/502/ 503/504 | SERVER\_ERROR            | Something went wrong on Klevu’s end.                                              | \[\{"message":"Something went wrong on Klevu’s end. Please contact Klevu support at https\://help.klevu.com/support/tickets/new" }]                                                                                                                                                                                                           |






[title] CMS content
[path] JSON API/Examples/Batch Updates/

To index  CMS content, please send the data in the format mentioned below:

:::BlockQuote
\[
&#x20;   \{
&#x20;       "id": "cms\_1",
&#x20;       "type": "KLEVU\_CMS",
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "CMS Title"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg"
&#x20;               }
&#x20;           },
&#x20;           "url": "http\://magento246.com/products/comfy-chair-001",
&#x20;           "shortDescription": \{
&#x20;               "default": "Comfortable Chair"
&#x20;           },
&#x20;           "description": \{
&#x20;               "default": "This is a very, very comfortable Chair"
&#x20;           },
&#x20;           "type": "Fashion"
&#x20;       }
&#x20;   }
]
:::


[title] Image
[path] JSON API/Examples/Partial Updates (Patch)/

Patching default image for a given product

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "add",
            "path": "/attributes/image/hover/url",
            "value": "https://fastly.picsum.photos/id/20/536/354.jpg?hmac=JRdy7LAV1wQa9JGfg21bQmuzBkh0P9HV3xwjmTEM0oQ"
        }
    ]
}
```
:::

Patching image hover for a given product

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "add",
            "path": "/attributes/image/default",
            "value": {                    
                "url" : "https://fastly.picsum.photos/id/20/536/354.jpg?hmac=JRdy7LAV1wQa9JGfg21bQmuzBkh0P9HV3xwjmTEM0oQ"
            }
        }
    ]
}
```
:::


[title] Simple Products
[path] JSON API/Examples/Batch Updates/

Following is a sample payload with required data points to index products:

:::ApiMethodV2
```json
{
  "name": "Add Products API",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/batch",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "json",
        "code": "[\n  {\n    \"id\": \"1\",\n    \"type\": \"KLEVU_PRODUCT\",\n    \"attributes\": {\n      \"name\": { \"default\": \"Product 1\" },\n       \"image\": \n       {  \n        \"default\":{\n          \"url\": \"https://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg\"\n        }\n      },\n      \"price\": {\n        \"USD\":{\n          \"defaultPrice\": 100,\n          \"salePrice\":80\n        },\n        \"GBP\":{\n         \"defaultPrice\": 90,\n         \"salePrice\":70\n        }\n      },\n      \"url\": \"https://test.myshopify.com/products/comfy-chair-001\",\n      \"inStock\": true,\n      \"shortDescription\": { \"default\": \"Comfortable Chair\" },\n      \"description\": { \"default\": \"This is a very very comfortable Chair\" }\n    }\n  },\n  {\n    \"id\": \"2\",\n    \"type\": \"KLEVU_PRODUCT\",\n    \"attributes\": {\n      \"name\": { \"default\": \"Product 2\" },\n      \"image\": \n       {  \n        \"default\":{\n          \"url\": \"https://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg\"\n        }\n      },\n      \"price\": {\n        \"USD\":{\n          \"defaultPrice\": 90,\n          \"salePrice\":80\n        },\n        \"GBP\":{\n         \"defaultPrice\": 70,\n         \"salePrice\":60\n        }\n      },\n      \"url\": \"https://test.myshopify.com/products/comfy-chair-002\",\n      \"inStock\": true,\n      \"shortDescription\": { \"default\": \"Comfortable Chair\" },\n      \"description\": { \"default\": \"This is a very very comfortable Chair\" }\n    }\n  }\n]",
        "customLabel": "Request Body (JSON)"
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n  \"message\": \"Job submitted successfully.\",\n  \"jobId\": \"job-123\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "add-products-api",
  "legacyHash": "DFqrJS2SUSvkCRhPAtENT"
}
```
:::

:::hint{type="info"}
The payload is an array of objects, meaning, you can submit multiple items for indexing in a single request and recommended too. There is no limit to the number of objects in a request, but the total size of the request should be under 2MB. Please plan your batch size accordingly.
:::


[title] Swagger/OpenAPI Specification
[path] JSON API/

:::hint{type="info"}
To access the data indexing API definition on the Swagger online editor, please click the [link](https://editor.swagger.io/?url=https://klevu-public-files.s3.eu-west-1.amazonaws.com/publish/klevu-indexing-p1.yaml)
:::



:::Swagger
```json
{
  "jsonFileLocation": "https://klevu-public-files.s3.eu-west-1.amazonaws.com/publish/klevu-indexing-p1.yaml",
  "headers": []
}
```
:::


[title] Relations
[path] JSON API/Examples/Partial Updates (Patch)/

Patching parent and category relations for a given product.&#x20;

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "replace",
            "path": "/relations",
            "value": {
                "parentProduct": {
                    "values": [
                        "PARENT_PRODUCT_001"
                    ]
                },
                "categories": {
                    "values": [
                        "CAT001",
                        "CAT002"
                    ]
                }
            }
        }
    ]
}
```
:::


[title] Swatches
[path] JSON API/Examples/Batch Updates/

If the complex product uses swatches in the product rendering, then swatch data can be indexed. Refer to the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8) for the details.&#x20;

:::hint{type="info"}
Swatch details need to be calculated and have to be indexed in all the variants. This calculation needs to be done at your end, Klevu does not calculate how many variants are available in the given swatch detail. These details are returned in the API response for the front end to use for rendering purposes.
:::


[title] Additional Data
[path] JSON API/Examples/Batch Updates/



There might be cases where you need to index certain attributes only for front-end rendering purposes. E.g. You want to index a complex json object, which is not indexed or used for merchandising, but only to render in the frontend and used in JavaScript, then you can use the “additionalDataToReturn” attribute.

:::BlockQuote
\[
&#x20; \{
&#x20;   "id": "1",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 1" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "s",
&#x20;      "additionalDataToReturn": \{
&#x20;       "myAttribute" : "my value",
&#x20;       "border-color" : "red",
&#x20;       "card-height" : "30px"
&#x20;      }
&#x20;   }
&#x20; }
]
:::

This will index a special attribute “**additionalDataToReturn**” in the product. In the Storefront API, request this attribute to be returned and you will get the data indexed as-is.

[title] Name
[path] JSON API/Examples/Partial Updates (Patch)/

Patching name for a list of given products.&#x20;

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "replace",
            "path": "/attributes/name",
            "value": {
                "default": "Comfortable Chair ITEM001"
            }
        }
    ],
    "ITEM002": [
        {
            "op": "replace",
            "path": "/attributes/name",
            "value": {
                "default": "Comfortable Chair ITEM002"
            }
        }
    ]
}
```
:::


[title] Prices
[path] JSON API/Examples/Partial Updates (Patch)/

Patching prices for a given product

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "add",
            "path": "/attributes/price",
            "value": {
                "USD" : {
                    "salePrice" : 50.00,
                    "defaultPrice" : 70.00,
                    "toPrice" : 70.00,
                    "startPrice" : 50.00
                },
                "GBP" : {
                    "salePrice" : 50.00
                }
            }
        }
    ]
}
```
:::

Patching prices for specific currencies when multiple currencies are submitted.

:::CodeblockTabs
Request Body

```json
{
    "ITEM001": [
        {
            "op": "add",
            "path": "/attributes/price/USD",
            "value": {                    
                "salePrice" : 50.00,
                "defaultPrice" : 70.00,
                "toPrice" : 70.00,
                "startPrice" : 50.00                
            }
        }
    ]
}
```
:::


[title] Visibility
[path] JSON API/Examples/Batch Updates/

By default, all the products that are indexed will be available in search and category API. For any reason, if there is a requirement that the product should be visible in any one of those or should not be coming up in either of those APIs, then it can be achieved by indexing the products with a special visibility attribute.&#x20;

Kindly refer to the Search API document on how to use the visibility feature at the storefront API. Following is the example of indexing the visibility value for different products for different use cases. “**search**” is used to make the product visible in Search API and “**catalog**” is used for Category pages.

:::BlockQuote
\[
&#x20; \{
&#x20;   "id": "1",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 1" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "s",
&#x20;      "visibility": \[
&#x20;         "search"
&#x20;     ]
&#x20;   }
&#x20; },
&#x20; \{
&#x20;   "id": "2",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;    "name": \{ "default": "Product 2" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "m",
&#x20;      "visibility": \[
&#x20;         "catalog"
&#x20;     ]
&#x20;   }
&#x20; },
&#x20; \{
&#x20;   "id": "3",
&#x20;   "type": "KLEVU\_PRODUCT",
&#x20;   "attributes": \{
&#x20;     "name": \{ "default": "Product 3" },
&#x20;      "brand" : "UCB",
&#x20;      "size" : "l",
&#x20;      "visibility": \[
&#x20;         "search",
&#x20;         "catalog"
&#x20;     ]
&#x20;   }
&#x20; }
]
:::

:::hint{type="info"}
In case you are using the visibility feature, then remember to index the visibility with both search and catalog for all the products that should be visible at both places.
:::


[title] Categories
[path] JSON API/Examples/Batch Updates/

If you are using category merchandising and want to associate products with the categories, then first index a category item and then index products by creating their relationship with the category. Products can be mapped to multiple categories. Following is an example of how to do it.

:::BlockQuote
\[
&#x20;   \{
&#x20;       "id": "men-shirts",
&#x20;       "type": "KLEVU\_CATEGORY",
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirts"
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/collections/men-shirts",
&#x20;           "categoryPath": "Mens;Shirts"
&#x20;       }
&#x20;   },
&#x20;   \{
&#x20;       "id": "1",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "relations": \{
&#x20;           "categories": \{
&#x20;               "values": \[
&#x20;                   "men-shirts"
&#x20;               ]
&#x20;           }
&#x20;       },
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg"
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt",
&#x20;           "shortDescription": \{
&#x20;               "default": "This is a black shirt available in different sizes."
&#x20;           }
&#x20;       }
&#x20;   },
&#x20;   \{
&#x20;       "id": "2",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "relations": \{
&#x20;           "parentProduct": \{
&#x20;               "values": \[
&#x20;                   "1"
&#x20;               ]
&#x20;           },
&#x20;           "categories": \{
&#x20;               "values": \[
&#x20;                   "men-shirts"
&#x20;               ]
&#x20;           }
&#x20;       },
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg"
&#x20;               }
&#x20;           },
&#x20;           "price": \{
&#x20;               "GBP": \{
&#x20;                   "salePrice": 80
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt-s",
&#x20;           "shortDescription": \{
&#x20;               "default": "Black Shirt"
&#x20;           },
&#x20;           "size": "s"
&#x20;       }
&#x20;   },
&#x20;   \{
&#x20;       "id": "3",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "relations": \{
&#x20;           "parentProduct": \{
&#x20;               "values": \[
&#x20;                   "1"
&#x20;               ]
&#x20;           },
&#x20;           "categories": \{
&#x20;               "values": \[
&#x20;                   "men-shirts"
&#x20;               ]
&#x20;           }
&#x20;       },
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/comfortable-office-chair.jpg"
&#x20;               }
&#x20;           },
&#x20;           "price": \{
&#x20;               "GBP": \{
&#x20;                   "salePrice": 100
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt-m",
&#x20;           "shortDescription": \{
&#x20;               "default": "Black Shirt"
&#x20;           },
&#x20;           "size": "m"
&#x20;       }
&#x20;   }
]
:::

:::hint{type="info"}
- For a complex product, ensure mapping all variants to the category.
- Items of different types like categories, products, etc can be part of the same request payload.
- Order should be maintained when objects are being related i.e. If you are mapping a product to a category, then the category should be created before the product.
:::


[title] Deletes
[path] JSON API/Examples/Batch Updates/

If a particular item is no longer available in the catalog, then you need to call the Delete API to get it removed from the index.&#x20;

:::BlockQuote
Request URL: https\://indexing-api.ksearchnet.com/v2/batch/delete
Request Method: PUT
Request Headers:
X-KLEVU-TIMESTAMP=2023-06-19T00:00:00.000Z
X-KLEVU-APIKEY=klevu-1234567890
X-KLEVU-AUTH-ALGO=HmacSHA384
Content-Type=application/json
Request body:
\{
&#x20; "ids": \[
&#x20;   "3", "2", "men-shirts"
&#x20; ]
}
:::

:::hint{type="info"}
If deleting a variant from a complex product causes any of the fields to change for other variants, e.g. startPrice and toPrice, then you need to index the other variants again.
:::


[title] Complex products
[path] JSON API/Examples/Batch Updates/

In the [Simple Products](docId:6CzVBlzOJ5qVAHkJfMZAF), we saw how to index products. Let's say you have a complex product like a Shirt, available in S and M sizes. The following example shows how to index this complex product. Some other fields are left out for simplicity.

:::BlockQuote
\[
&#x20;   \{
&#x20;       "id": "1",
&#x20;       "type": "KLEVU\_PARENT\_PRODUCT",
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/black-shirt.jpg"
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt",
&#x20;           "shortDescription": \{
&#x20;               "default": "This is a black shirt available in different sizes."
&#x20;           }
&#x20;       }
&#x20;   },
&#x20;   \{
&#x20;       "id": "2",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "relations": \{
&#x20;           "parentProduct": \{
&#x20;               "values": \[
&#x20;                   "1"
&#x20;               ]
&#x20;           }
&#x20;       },
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/black-shirt.jpg"
&#x20;               }
&#x20;           },
&#x20;           "price": \{
&#x20;               "USD": \{
&#x20;                   "defaultPrice": 100,
&#x20;                   "salePrice": 80
&#x20;               },
&#x20;               "GBP": \{
&#x20;                   "defaultPrice": 90,
&#x20;                   "salePrice": 70
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt-s",
&#x20;           "shortDescription": \{
&#x20;               "default": "Black Shirt"
&#x20;           },
&#x20;           "size": "s"
&#x20;       }
&#x20;   },
&#x20;   \{
&#x20;       "id": "3",
&#x20;       "type": "KLEVU\_PRODUCT",
&#x20;       "relations": \{
&#x20;           "parentProduct": \{
&#x20;               "values": \[
&#x20;                   "1"
&#x20;               ]
&#x20;           }
&#x20;       },
&#x20;       "attributes": \{
&#x20;           "name": \{
&#x20;               "default": "Shirt"
&#x20;           },
&#x20;           "image": \{
&#x20;               "default": \{
&#x20;                   "url": "https\://4.imimg.com/data4/AO/DA/MY-24693421/black-shirt.jpg"
&#x20;               }
&#x20;           },
&#x20;           "price": \{
&#x20;               "USD": \{
&#x20;                   "defaultPrice": 100,
&#x20;                   "salePrice": 80
&#x20;               },
&#x20;               "GBP": \{
&#x20;                   "defaultPrice": 90,
&#x20;                   "salePrice": 70
&#x20;               }
&#x20;           },
&#x20;           "url": "https\://test.myshopify.com/products/black-shirt-m",
&#x20;           "shortDescription": \{
&#x20;               "default": "Black Shirt"
&#x20;           },
&#x20;           "size": "m"
&#x20;       }
&#x20;   }
]
:::

Here we have indexed 3 items, first the parent product, then the two variants of the product. A few points to note:

- The parent product needs to be indexed before indexing the variants.
- The “**relations**” field represents the relation of the item with other items in your catalog. Here we have used the “`parentProduct`" relation at the variant level to map them to the parent product.
- “size” is a custom attribute used to provide different values of the variant.
- Under prices, observe that the sale price is different for variants, but startPrice and toPrice are calculated based on all the variants of the complex product and indexed into all variants. This helps in rendering the startPrice in the product card on the website.
- “**url**”: If variants have variant specific URLs, then use that for indexing else use the same product URL for all variants.

:::hint{type="info"}
* All the attributes have to be repeated for all variants.
* Start and To prices have to be calculated and sent for each variant. Due to this, if any variant being deleted causes a change in either of the two values, then all other variants need to be indexed again.
:::


[title] Job Tracking
[path] JSON API/

### Overview

The **Indexing Job Tracking API** is designed to monitor and manage the progress of jobs related to batch processing. These APIs allow users to track the status of jobs as they move through different stages: DONE, PROCESSING, and INITIALIZING.

Key features of the API include:

- **Job Status&#x20;**
  - Retrieve the current state of the job, helping to understand whether a job is completed (DONE), still in progress (PROCESSING), or just beginning (INITIALIZING).
- **Timestamps**

  &#x20;Access each job's start and end times, providing a timeline for tracking the job's execution duration.
- **Document Management**: Manage documents involved in the job, including:
  - **Docs in Request**

    The documents submitted in the job request.
  - **Docs Affected**

    &#x20;Documents that are impacted due to operations like inheritance, category updates.&#x20;
  - **Docs Completed**

    Track the document IDs of those that have successfully completed processing.

### Schema (Response)

```json
{
	"apiKey": "klevu-xxxxxxxxxxxxxxx",
	"jobId": "890709879342",
	"docsInRequest": ["cat1"],
	"docsAffected": [ "product1", "product2", ... ],
	"docsCompleted: [ "product1", ... ],
	"status": "INITIALIZING/PROCESSING/DONE",
	"jobType" : "BATCH_INDEX/BATCH_INDEX_PARTIAL_SAVE/BATCH_INDEX_DELETE/CHANNEL_DELETE/CHANNEL_UPDATE",
	"startTime": "2023-08-24T10:10:10.100Z",
	"endTime": "023-08-24T10:10:10.100Z"
}
```

### Understanding the response parameters&#x20;

**apiKey**&#x20;

This is the store's JS API Key. It can be obtained using [link](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)

**jobId**&#x20;

The unique ID represents an individual job.&#x20;

**docsInRequest**&#x20;

Originally received document id as part of user actions.

**docsAffected**&#x20;

All the document id which is going to be affected by user action eg. if we are updating the category name and it will affect 20 documents that is attached to that category, the service will get those 20 document IDs as affected documents.

**docsCompleted**&#x20;

All document IDs that are successfully cleared from the processing.&#x20;

**jobType**

Indicates the type of job submitted.

**status**

The status of the job, at the moment, we support three statuses. Here are the details: INITIALIZING - the job was accepted and is queued for processing. PROCESSING - Job is progressing through the system and Search is getting updated. DONE - Job is complete and all affected documents are updated on Search.

**startTime**

The timestamp when the job was initiated.&#x20;

**endTime** &#x20;

when status is changed to DONE, the system will use the timestamp to set this attribute in schema, it will determine at which time all documents were completed from the job.&#x20;

### API Specifications&#x20;

Please refer to **Job tracking&#x20;**&#x73;ection of [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8)&#x20;


[title] Overview
[path] JSON API/

When working with our JSON API, it’s important to structure your HTTP requests correctly to ensure successful execution. Here’s a brief overview to guide you:&#x20;

### Authentication

To authenticate your requests, certain headers must be included. Please refer to the [Authentication Documentation]() for detailed instructions on the required headers and authentication process.

### Request Body

The request body should be a JSON object tailored to the specific API operation you intend to execute. Refer to the URL and HTTP method type (GET, PUT PATCH, etc.) as specified in the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8)

### Response

A successful request will return an HTTP 200 status code. For information on other possible status codes and their corresponding response messages, consult the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8)

### Limits

All APIs generally have a request size limit of 2MB. In case of For additional validations or specific limits for certain APIs, refer to the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8)

### Record Structure

In Klevu, each item needs to be indexed, i.e. if you have a complex product, like a Shirt, available in different sizes and colors, then you should index the Parent product “Shirt” and all the variants available as a different item in Klevu. Following are some of the key properties of the Item to understand how to structure a product.

- “**id**” field: Each item should have the unique **“id”**. Each item being submitted in the request should have the ID defined in the whole catalog. Even for complex products, ensure that parent products and variants have unique IDs in the full catalog. E.g. I cannot have a parent product with id “1” and variants with id “1”, “2” and “3”. Here parent and variant have a conflict at id “1”. Same way, I cannot have a CMS page with id “1” if there exists an item with id “1”.
- Th&#x65;**&#x20;“type”** field represents the type of item. For catalog items, “`KLEVU_PRODUCT`“ is used. For other types, please refer to ItemType from [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8)
- The “**attributes**” field represents all the attributes of the item. The basic attributes that you will include in the product are “name”, “URL”, and “price”. There are other standard attributes available that can be used and defined in the [Swagger/OpenAPI Specification](docId\:W5iVV5Q4JjBfFywxDS5p8).
  - “**name**”: You might notice that text fields like name, and description have defined values as `{ "default": "Product 1" }`
    *Fields with text value have been defined in the above format using "default". It will help us to expand the definition for other use cases in the future. For the time being, all text values have to follow the pattern as you see in the example.*
  - “**URL**”: URL is critical for the item being indexed and that is used to redirect the end-user on your site to the relevant page. It should typically have a value of the PDP page for the product, a Category page for the category, etc. For different variants in the complex product, if your platform supports variant-specific URLs, then it is recommended to use the variant flavor of URL, else you can also give a common parent product URL for all the variants.
  - “**price**“: Prices are mandatory for the products being indexed. This is a list of different prices and “type” defines the use of the price. “currency” needs to be defined for each price, even if the store is using a single currency, it needs to be defined for each price of the product. If you are indexing multi-currency prices, then ensure that you give value for each currency for each product.
    - “salePrice” is the mandatory type to be defined for each currency for each product. This is the price after all applicable discounts and will be displayed in the rendered product.
    - “defaultPrice” is the original price, if defined, can be used to show a strikethrough while rendering the products.
- The “**relations**” field represents the relation of the item with other items in your catalog. We can map a parent and child product in a Complex product or map products in categories using relations. You will see this in action in one of the [Examples](docId:4Nx4iAIQ1Ea1vwZYmf7XL).
- The “**channels**” field is used to represent alternative values of the properties for different channels or groups. E.g. we use it for defining a different price for a customer group on my site. Refer to the example [Customer Groups](docId:2FU3QL4JhM2BVvjsgXSjB) to understand how to use this in detail.

### Example request

:::ApiMethodV2
```json
{
  "name": "showcasing how to register a custom attribute ",
  "method": "PUT",
  "url": "https://indexing-api.ksearchnet.com/v2/attributes/custom_attribute",
  "description": "",
  "tab": "examples",
  "examples": {
    "languages": [
      {
        "id": "xOBGdm4j1d4of8rZLyuHq",
        "language": "curl",
        "code": "curl --location --request PUT 'https:///v2/attributes/custom1' \\\n--header 'X-KLEVU-AUTH-ALGO: HmacSHA384' \\\n--header 'X-KLEVU-TIMESTAMP: 2023-07-10T08:38:00Z' \\\n--header 'X-KLEVU-APIKEY: klevu-1592574318858490' \\\n--header 'Content-Type: application/json' \\\n--header 'Authorization: Bearer YQVmPq63wosB760EAkUNdomeI3Rlm+EFKdg7weXnIFewCCD6eJQJJ5h/w/HdtFpG' \\\n--data '{\n    \"label\": {\n        \"default\": \"custom_attribute\"\n    },\n    \"searchable\": true,\n    \"filterable\": false,\n    \"returnable\": false,\n    \"datatype\": \"STRING\"\n}'",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "xOBGdm4j1d4of8rZLyuHq"
  },
  "results": {
    "languages": [
      {
        "id": "blif1oGwvbqovmU2FClQc",
        "language": "200",
        "customLabel": "",
        "code": "{\n    \"message\": \"Attribute saved successfully\"\n}"
      }
    ],
    "selectedLanguageId": "blif1oGwvbqovmU2FClQc"
  },
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "name": "X-KLEVU-AUTH-ALGO",
        "kind": "required",
        "type": "string",
        "description": "This is the algorithm used to create the security bearer token. ",
        "children": []
      },
      {
        "name": "X-KLEVU-TIMESTAMP",
        "kind": "required",
        "type": "string",
        "description": "This should be your current time while generating the request. It is used to keep the request secured and discourage request relays.",
        "children": []
      },
      {
        "name": "X-KLEVU-APIKEY",
        "kind": "required",
        "type": "string",
        "description": "This is the API Key of your store. Please refer to the Klevu Merchant Centre manual to understand where to get this key from.",
        "children": []
      },
      {
        "name": "Content-Type",
        "kind": "required",
        "type": "string",
        "description": "This needs to be application/JSON as this request body contains a JSON.",
        "children": []
      },
      {
        "name": "Authorization",
        "kind": "required",
        "type": "string",
        "description": "This is the generated security token that authenticates the request.",
        "children": []
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "showcasing-how-to-register-a-custom-attribute",
  "legacyHash": "k22I-gmAg1fV7t59JZMcd"
}
```
:::




[title] XML API
[path] /

The Klevu Indexing API is organized around [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer). Our API has predictable resource-oriented URLs, accepts XML request bodies, returns [XML-encoded](https://en.wikipedia.org/wiki/XML) responses, and uses standard HTTP response codes, authentication, and verbs.&#x20;

Every record (e.g. a product, category, cms page etc.) sent to Klevu is maintained in a dedicated index for the respective store. The Indexing API is used for adding, updating or deleting records from this index.

The Indexing API requires that you first authenticate yourself to the Klevu servers. As a result of this authentication, you are provided with a **Session ID &#x20;**&#x77;hich you can use for subsequent requests to the Klevu servers.

## API Key & Endpoint

You must have a Klevu Search account to use the Klevu API. Please access the [Shop Info section](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-js-rest-api-keys-cloud-search-url-from-klevu-dashboard-) of your Klevu Merchant Centre to retrieve the following credentials.

- **REST API Key** *(private key)* for submitting data to be indexed, eg. abcdefoobar==.
- **Product Synchronization URL** for submitting data to be indexed, eg. rest.klevu.com.

## What is a Record?

With Klevu a record can be a **Product**, a **Category page** or a **CMS page** that you want to index and make available in search results.
It can also be a custom record type such as a **Store** or **Recipe** or something like that.

When you submit a record for addition or update, you must submit the record with all of its details provided.
A list of mandatory and optional fields is provided below.
When you submit a record for deletion, however, you only need to submit its unique ID.

:::ExpandableHeading
## Attributes

**id** <font color="#8792a2">string</font> <font color="#8792a2">| </font>required

This is the unique identifier of a record. Klevu will use this ID for indexing, analytics and merchandising.

**itemGroupId** <font color="#8792a2">string</font> <font color="#8792a2">| </font>optional

If your data contains a shirt in 2 different colours and 3 different sizes, you must submit 6 product variants. To indicate which group each variant belongs to, specify a common value in this itemGroupId element.



**name** <font color="#8792a2">string</font> <font color="#8792a2">| </font>required

This is the name or title of your record.&#x20;



**sku** <font color="#8792a2">string</font> <font color="#8792a2">| </font>required

This is the unique SKU of the record, or Stock Keeping Unit.



**url** <font color="#8792a2">string</font> <font color="#8792a2">| </font>required

This is the URL where shoppers will be taken to when the record is clicked in the Klevu Search results. This must be a fully qualified URL, beginning `http://` or `https://`. Note that you may receive a 400: Bad Request if you submit a base URL that has not been configured in your Klevu Merchant Centre.



**currency** <font color="#8792a2">string</font> <font color="#8792a2">| </font>required

The currency code of the prices specified below, e.g. EUR, USD, GBP.



**price** <font color="#8792a2">double</font> <font color="#8792a2">| </font>required

The original price of your product, before any discounts. This can be used as was price when used in conjunction with salePrice. In the case of a non-product record, 0.0 must be provided as the value.



Permitted characters in this field are 0 to 9 (digits) and . (dot) for adding a decimal point. For example, 12999.00 is a valid value, however $12999 or 12,999.00 are not.Please specify the currency information in the separate currency element.

****

**salePrice** <font color="#8792a2">double</font> <font color="#8792a2">| </font>required

This is the final price of your product, after all applicable discounts. This can be used as 'now price' when used in conjunction with price. The format of this field is the same as price.



**startPrice** <font color="#8792a2">double</font> <font color="#8792a2">| </font>optional

If your record has multiple variants, this field can be used to show the lowest price across all variants, for displaying "as low as £100".



**toPrice** <font color="#8792a2">double</font> | optional

&#x20;If your record has multiple variants, this field can be used to show the highest price across all variants, for use in conjunction with startPrice to display "from £100 to £200".

***

**groupPrices** <font color="#8792a2">string</font> | optional

This field is mostly commonly used in Magento integrations for the customer group prices to be rendered on the frontend. The format of this field is: `1:General:100.00`. There are three colon : separated values in each price grouping. The first value represents the ID of the group, the second is the label, and the third is the price for that group.&#x20;



Please see the XML to the right for a full example.



**otherPrices** <font color="#8792a2">string </font>| optional
This is an improvement over `groupPrices`, in that the values specified here can also be used in conjunction with `priceFieldSuffix` to retrieve dynamic prices based on currencies and customer groups.



The format of this field is: `price_USD-group_1:100.00`. There are two colon `:` separated values in each price grouping. The first value represents the ID of the group and the second is the price for that group.The ID is made up of the following format: `price type_currency code-group_id`, with the group ID being optional if you are not using currencies.



Please see the XML to the right for a full example of the possible variations.



**inStock** <font color="#8792a2">string</font> | optional

This attribute indicates if your record is in stock or not. Provide a value of yes if in stock, and no otherwise. In case if you are not submitting stock status, **Klevu will consider product as out of stock.** Please configure [Klevu stock setting](https://help.klevu.com/support/solutions/articles/5000871482-hide-out-of-stock-products) to show out of stock products.



**category** <font color="#8792a2">string</font> | required

This attribute indicates the most specific category of the record being submitted. For example, if your product belongs to the following categories:&#x20;

- Mobiles & Accessories
  - Tablets
- Promotions
  - New In

It is only **Tablets** and **New In** that should be specified here, separated by a semicolon` ;,` for example: `Tablets;New In.`



**listCategory** <font color="#8792a2">string</font> | required
This field contains up to three pieces of data, depending on your use case. Each section of the field must be separated by a double semicolon `;;.`&#x20;

****

- **Record Type: &#x20;**&#x54;he first part is always required, a record type. You MUST provide one of the following values, whichever is most appropriate for your record:&#x20;
  - KLEVU\_PRODUCT  for Product records&#x20;
  - KLEVU\_CATEGORY  for Category records&#x20;
  - KLEVU\_CMS  for CMS Pages or Blog Articles&#x20;
  - YOUR\_TYPE  for your own custom entity, eg: ACME\_RECIPE&#x20;

- **Category Hierarchy:**  The second part is made up of the entire hierarchies of applicable categories the record belongs to, with each category within the hierarchy separated by a single semicolon ;. Using the same example as in category above, the following would be submitted for this section: Mobiles & Accessories;Tablets;;Promotions;New In. Group ID:  The third part is optional, and only needed if you plan to use the visibilityGroupID feature in API requests to control which customer groups can see which records. This is made up of a double semicolon ;; separated list of all applicable customer groups for this record, eg: customer\_group\_1;;wholesale\_group.See the XML to the right for a full example.



**image** <font color="#8792a2">string</font> | optional

This is the URL of an associated image for your record. This must be a fully qualified URL, beginning  `http:// ` or`  https://`



**imageHover** <font color="#8792a2">string</font> | optional

This field can be used to specify an additional image for your record to be used on mouse hover. The format is the same as for  image.



**shortDesc** <font color="#8792a2">string</font> | optional

The short description for your record. This field can be used to display a smaller description of a record in the search results.



**desc** <font color="#8792a2">string</font> | optional

The long description for your record. This can also be configured to be considered in search results, in which case both this value and  shortDesc  will become searchable.



**other** <font color="#8792a2">string</font> | optional

Use this field to specify filterable attributes for your product, to be used as facets. The value is made up of three values separated by colon ` :` , then each attribute is separated by a semicolon  `; : `&#x20;

- Attribute Code
- Caption or Label
- Value(s)&#x20;

For example:  occassion\:Occassion\:Christmas,Evening Wear . The  **attribute code**  here is a unique identifier of your attribute. The&#x20;**&#x20;attribute caption**  is used as the heading of your filter when displaying search results. If the attribute code, caption or values contain a comma, colon or semi-colon, they must be replaced with a space.



**otherAttributeToIndex** <font color="#8792a2">string</font> | optional

The format of this element is the same as the format of the `other element` above. The difference between the two is that  `other`  is used for displaying facets whereas  `otherAttributeToIndex`  is used for indexing and searching only. Populate this field with any attributes you want to be searchable, but not used as a facet.

****

**boostingAttribute** <font color="#8792a2">string</font> | optional

The score provided here is multiplied with the relevancy score to boost records at search time. Any decimal value between the range of 0.1 to 999 can be provided here. Provide a value greater than 1 to boost a record up the rankings. To de-boost or demote a record, provide a number that is greater than 0 and less than 1.



**rating&#x20;**<font color="#8792a2">string</font> | optional

A score between 0 and 5. This can be used for displaying a star rating with each record, and can also be used to apply a sort order of the highest-rated items.



**rating\_count&#x20;**<font color="#8792a2">string</font> | optional

Use this field to specify the number of ratings given by customers for your product.


**tags** <font color="#8792a2">string</font> | optional

Use this field to specify any important keywords applicable for your records.



**swatches** <font color="#8792a2">string</font> | optional

If your record has many variants, you can specify swatch data to be used across them. You must specify the same swatch data for all variants, and the format is made up of four elements, which is repeated with a suffix of 1, 2, 3, etc. for each variant:

- variantId1:  The Klevu ID of the variant, eg. 123-ABC.&#x20;
- variantColor1: The colour of the variant. Base CSS color name or HEX value.&#x20;
- variantSwatchImage1:  (optional) The URL of the image to be displayed as the swatch itself.&#x20;
- variantImage1:  The product image that this swatch represents.  See the XML below full example.



**additionalDataToReturn** <font color="#8792a2">string</font> | optional

If you have some data that you would like to be returned with the search response, populate that data in this field. The structure can be anything you like, but we recommend JSON. If you do not see this in your response data, please contact Klevu Support by submittng a support [ticket](https://help.klevu.com/support/tickets/new)
:::

## Requesting a Session ID

Use this call to authenticate yourself to the Klevu Indexing servers. In the response, you will be provided with a **Session ID** which you should use for all subsequent requests to the Klevu servers.

You will need your **REST API Key** and **Product Synchronization URL**. Please refer to the [Prerequisites](https://docs.klevu.com/apis/data-indexing#MUoVK) section for more information.

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<productSynchronizationURL>/rest/service/startSession",
  "name": "Session ID",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "kind": "required",
        "name": "Authorization",
        "type": "string",
        "description": "Your Klevu REST API Key, eg. abcdefoobar=="
      }
    ],
    "bodyDataParameters": [],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "es3bXLF4dy_6T59tiQiUm",
        "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<message>\n  <status>SUCCESS</status>\n  <sessionId>Some-Session-ID</sessionId>\n</message>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "es3bXLF4dy_6T59tiQiUm"
  },
  "examples": {
    "languages": [
      {
        "id": "9xe3U_6kfgSQDG_vz0FVa",
        "code": "curl --location --request POST 'http://rest2.ksearchnet.com/rest/service/startSession' \\\n--header 'Authorization:  abcdefoobar=='",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "9xe3U_6kfgSQDG_vz0FVa"
  },
  "description": "The end point is used for obtaining session id. ",
  "currentNewParameter": {
    "label": "Header Parameter",
    "value": "headerParameters"
  },
  "autoGeneratedAnchorSlug": "session-id",
  "legacyHash": "8SZoXV_MK1UiYY0himHVi"
}
```
:::

## Adding New Records

You must provide each record in full, including all mandatory parameters for every record you submit.

**Prerequisites:**
You will also need a **Session ID**, please see the section above on [Requesting a Session ID]().

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<productSynchronizationURL>/rest/service/addRecords",
  "name": "Add New Records",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "kind": "required",
        "name": "Content-Type",
        "type": "String",
        "description": "The content type for the request. Please set this to application/xml. "
      }
    ],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "data-raw",
        "type": "string",
        "description": "The xml string for submitting record data. "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "gh1drPGG88hpmPjQCpg6D",
        "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<message>\n  <status>SUCCESS</status>\n  <msg>3 records are marked for ADDITION</msg>\n</message>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "gh1drPGG88hpmPjQCpg6D"
  },
  "examples": {
    "languages": [
      {
        "id": "Tqeg_tAzlX1Uewf-czPEm",
        "code": "curl --location --request POST 'https://<productSynchronizationURL>/rest/service/addRecords' \\\n--header 'Content-Type: application/xml' \\\n--data-raw '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<request>\n    <sessionId>Your-Session-ID</sessionId>\n    <records>\n        <record>\n            <pairs>\n                <!-- IDs -->\n                <pair>\n                    <key>id</key>\n                    <value>123-ABC</value>\n                </pair>\n                <pair>\n                    <key>itemGroupId</key>\n                    <value>123</value>\n                </pair>\n\n                <!-- Product Information -->\n                <pair>\n                    <key>sku</key>\n                    <value>SKU-123-ABC</value>\n                </pair>\n                <pair>\n                    <key>name</key>\n                    <value>My Product Name</value>\n                </pair>\n                <pair>\n                    <key>inStock</key>\n                    <value>yes</value>\n                </pair>\n                <pair>\n                    <key>url</key>\n                    <value>https://your-website.com/products/123.html</value>\n                </pair>\n                <pair>\n                    <key>image</key>\n                    <value>https://your-website.com/images/products/123-abc.jpg</value>\n                </pair>\n                <pair>\n                    <key>imageHover</key>\n                    <value>https://your-website.com/images/products/hover/123-abc.jpg</value>\n                </pair>\n\n                <!-- Product Descriptions -->\n                <pair>\n                    <key>shortDesc</key>\n                    <value>My Short Description</value>\n                </pair>\n                <pair>\n                    <key>desc</key>\n                    <value>My Longer Description</value>\n                </pair>\n\n                <!-- Prices -->\n                <pair>\n                    <key>currency</key>\n                    <value>GBP</value>\n                </pair>\n                <pair>\n                    <key>price</key>\n                    <value>150.00</value>\n                </pair>\n                <pair>\n                    <key>salePrice</key>\n                    <value>100.00</value>\n                </pair>\n                <pair>\n                    <key>startPrice</key>\n                    <value>50.00</value>\n                </pair>\n                <pair>\n                    <key>toPrice</key>\n                    <value>200.00</value>\n                </pair>\n                <pair>\n                    <key>otherPrices</key>\n                    <value>price_GBP:150.00;price_USD:200.00;salePrice_GBP:100.00;salePrice_USD:150.00;startPrice_GBP:50.00;startPrice_USD:100.00;toPrice_GBP:200.00;toPrice_USD:300.00;price_GBP-test_group_1:100.00;price_USD-test_group_1:150.00;salePrice_GBP-test_group_1:80.00;salePrice_USD-test_group_1:100.00;startPrice_GBP-test_group_1:30.00;startPrice_USD-test_group_1:50.00;toPrice_GBP-test_group_1:180.00;toPrice_USD-test_group_1:200.00;price_GBP-test_group_2:90.00;price_USD-test_group_2:140.00;salePrice_GBP-test_group_2:70.00;salePrice_USD-test_group_2:90.00;startPrice_GBP-test_group_2:20.00;startPrice_USD-test_group_2:40.00;toPrice_GBP-test_group_2:170.00;toPrice_USD-test_group_2:190.00</value>\n                </pair>\n                <pair>\n                    <key>groupPrices</key>\n                    <value>test_group_1:Test Group 1:80.00;test_group_2:Test Group 2:70.00</value>\n                </pair>\n\n                <!-- Categorisation -->\n                <pair>\n                    <key>category</key>\n                    <value>Sub Category A-2;Sub Category B-2</value>\n                </pair>\n                <pair>\n                    <key>listCategory</key>\n                    <value>KLEVU_PRODUCT;;Category A;Sub Category A-1;Sub Category A-2;;Category B;Sub Category B-1;Sub Category B-2;;test_group_1;;test_group_2</value>\n                </pair>\n\n                <!-- Attributes -->\n                <pair>\n                    <key>other</key>\n                    <value>color:Colour:red;occasion:Occasion:Christmas,Evening Wear</value>\n                </pair>\n                <pair>\n                    <key>otherAttributeToIndex</key>\n                    <value>brand:Brand Name:Nike,Adidas;gtin:GTIN:123456789</value>\n                </pair>\n                <pair>\n                    <key>rating</key>\n                    <value>3.5</value>\n                </pair>\n                <pair>\n                    <key>rating_count</key>\n                    <value>10</value>\n                </pair>\n                <pair>\n                    <key>tags</key>\n                    <value>keyword 1,keyword 2</value>\n                </pair>\n\n                <!-- Swatches -->\n                <pair>\n                    <key>variantId1</key>\n                    <value>123-ABC</value>\n                </pair>\n                <pair>\n                    <key>variantColor1</key>\n                    <value>Red</value>\n                </pair>\n                <pair>\n                    <key>variantSwatchImage1</key>\n                    <value>https://your-website.com/images/swatches/red.jpg</value>\n                </pair>\n                <pair>\n                    <key>variantImage1</key>\n                    <value>https://your-website.com/images/products/456-abc.jpg</value>\n                </pair>\n\n                <pair>\n                    <key>variantId2</key>\n                    <value>123-BCD</value>\n                </pair>\n                <pair>\n                    <key>variantColor2</key>\n                    <value>White</value>\n                </pair>\n                <pair>\n                    <key>variantSwatchImage2</key>\n                    <value>https://your-website.com/images/swatches/white.jpg</value>\n                </pair>\n                <pair>\n                    <key>variantImage2</key>\n                    <value>https://your-website.com/images/products/123-def.jpg</value>\n                </pair>\n\n                <!-- Miscellaneous -->\n                <pair>\n                    <key>boostingAttribute</key>\n                    <value>5</value>\n                </pair>\n                <pair>\n                    <key>additionalDataToReturn</key>\n                    <value>{\"some_arbitrary\": \"data to return\"}</value>\n                </pair>\n            </pairs>\n        </record>\n    </records>\n</request>'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Tqeg_tAzlX1Uewf-czPEm"
  },
  "description": "The end-point is used for adding new records to index. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "add-new-records",
  "legacyHash": "8XnxkImXkNEoraRLXKtpS"
}
```
:::

## Updating Existing Records

You must provide each record in full, including all mandatory parameters for every record you submit.

**Prerequisites:**
You will also need a **Session ID**, please see the section above on [Requesting a Session ID]().

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<productSynchronizationURL>/rest/service/updateRecords",
  "name": "Update Existing Records",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "kind": "required",
        "name": "Content-Type",
        "type": "String",
        "description": "The content type for the request. Please set this to application/xml. "
      }
    ],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "data-raw",
        "type": "string",
        "description": "The xml string for submitting record data. "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "gh1drPGG88hpmPjQCpg6D",
        "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<message>\n  <status>SUCCESS</status>\n  <msg>3 records are marked for UPDATING</msg>\n</message>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "gh1drPGG88hpmPjQCpg6D"
  },
  "examples": {
    "languages": [
      {
        "id": "Tqeg_tAzlX1Uewf-czPEm",
        "code": "curl --location --request POST 'https://<productSynchronizationURL>/rest/service/updateRecords' \\\n--header 'Content-Type: application/xml' \\\n--data-raw '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<request>\n    <sessionId>Your-Session-ID</sessionId>\n    <records>\n        <record>\n            <pairs>\n                <!-- IDs -->\n                <pair>\n                    <key>id</key>\n                    <value>123-ABC</value>\n                </pair>\n                <pair>\n                    <key>itemGroupId</key>\n                    <value>123</value>\n                </pair>\n\n                <!-- Product Information -->\n                <pair>\n                    <key>sku</key>\n                    <value>SKU-123-ABC</value>\n                </pair>\n                <pair>\n                    <key>name</key>\n                    <value>My Product Name</value>\n                </pair>\n                <pair>\n                    <key>inStock</key>\n                    <value>yes</value>\n                </pair>\n                <pair>\n                    <key>url</key>\n                    <value>https://your-website.com/products/123.html</value>\n                </pair>\n                <pair>\n                    <key>image</key>\n                    <value>https://your-website.com/images/products/123-abc.jpg</value>\n                </pair>\n                <pair>\n                    <key>imageHover</key>\n                    <value>https://your-website.com/images/products/hover/123-abc.jpg</value>\n                </pair>\n\n                <!-- Product Descriptions -->\n                <pair>\n                    <key>shortDesc</key>\n                    <value>My Short Description</value>\n                </pair>\n                <pair>\n                    <key>desc</key>\n                    <value>My Longer Description</value>\n                </pair>\n\n                <!-- Prices -->\n                <pair>\n                    <key>currency</key>\n                    <value>GBP</value>\n                </pair>\n                <pair>\n                    <key>price</key>\n                    <value>150.00</value>\n                </pair>\n                <pair>\n                    <key>salePrice</key>\n                    <value>100.00</value>\n                </pair>\n                <pair>\n                    <key>startPrice</key>\n                    <value>50.00</value>\n                </pair>\n                <pair>\n                    <key>toPrice</key>\n                    <value>200.00</value>\n                </pair>\n                <pair>\n                    <key>otherPrices</key>\n                    <value>price_GBP:150.00;price_USD:200.00;salePrice_GBP:100.00;salePrice_USD:150.00;startPrice_GBP:50.00;startPrice_USD:100.00;toPrice_GBP:200.00;toPrice_USD:300.00;price_GBP-test_group_1:100.00;price_USD-test_group_1:150.00;salePrice_GBP-test_group_1:80.00;salePrice_USD-test_group_1:100.00;startPrice_GBP-test_group_1:30.00;startPrice_USD-test_group_1:50.00;toPrice_GBP-test_group_1:180.00;toPrice_USD-test_group_1:200.00;price_GBP-test_group_2:90.00;price_USD-test_group_2:140.00;salePrice_GBP-test_group_2:70.00;salePrice_USD-test_group_2:90.00;startPrice_GBP-test_group_2:20.00;startPrice_USD-test_group_2:40.00;toPrice_GBP-test_group_2:170.00;toPrice_USD-test_group_2:190.00</value>\n                </pair>\n                <pair>\n                    <key>groupPrices</key>\n                    <value>test_group_1:Test Group 1:80.00;test_group_2:Test Group 2:70.00</value>\n                </pair>\n\n                <!-- Categorisation -->\n                <pair>\n                    <key>category</key>\n                    <value>Sub Category A-2;Sub Category B-2</value>\n                </pair>\n                <pair>\n                    <key>listCategory</key>\n                    <value>KLEVU_PRODUCT;;Category A;Sub Category A-1;Sub Category A-2;;Category B;Sub Category B-1;Sub Category B-2;;test_group_1;;test_group_2</value>\n                </pair>\n\n                <!-- Attributes -->\n                <pair>\n                    <key>other</key>\n                    <value>color:Colour:red;occasion:Occasion:Christmas,Evening Wear</value>\n                </pair>\n                <pair>\n                    <key>otherAttributeToIndex</key>\n                    <value>brand:Brand Name:Nike,Adidas;gtin:GTIN:123456789</value>\n                </pair>\n                <pair>\n                    <key>rating</key>\n                    <value>3.5</value>\n                </pair>\n                <pair>\n                    <key>rating_count</key>\n                    <value>10</value>\n                </pair>\n                <pair>\n                    <key>tags</key>\n                    <value>keyword 1,keyword 2</value>\n                </pair>\n\n                <!-- Swatches -->\n                <pair>\n                    <key>variantId1</key>\n                    <value>123-ABC</value>\n                </pair>\n                <pair>\n                    <key>variantColor1</key>\n                    <value>Blue</value>\n                </pair>\n                <pair>\n                    <key>variantSwatchImage1</key>\n                    <value>https://your-website.com/images/swatches/blue.jpg</value>\n                </pair>\n                <pair>\n                    <key>variantImage1</key>\n                    <value>https://your-website.com/images/products/123-abc.jpg</value>\n                </pair>\n\n                <pair>\n                    <key>variantId2</key>\n                    <value>123-BCD</value>\n                </pair>\n                <pair>\n                    <key>variantColor2</key>\n                    <value>White</value>\n                </pair>\n                <pair>\n                    <key>variantSwatchImage2</key>\n                    <value>https://your-website.com/images/swatches/white.jpg</value>\n                </pair>\n                <pair>\n                    <key>variantImage2</key>\n                    <value>https://your-website.com/images/products/123-def.jpg</value>\n                </pair>\n\n                <!-- Miscellaneous -->\n                <pair>\n                    <key>boostingAttribute</key>\n                    <value>5</value>\n                </pair>\n                <pair>\n                    <key>additionalDataToReturn</key>\n                    <value>{\"some_arbitrary\": \"data to return\"}</value>\n                </pair>\n            </pairs>\n        </record>\n    </records>\n</request>'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Tqeg_tAzlX1Uewf-czPEm"
  },
  "description": "The end-point is used for updating existing records to index. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "update-existing-records",
  "legacyHash": "2lleBKf_wDz2xX809FJbL"
}
```
:::

## Deleting Existing Records

You must provide the unique IDs of the records you wish to delete.

**Prerequisites:**
You will also need a **Session ID**, please see the section above on [Requesting a Session ID]().

:::ApiMethodV2
```json
{
  "tab": "examples",
  "url": "https://<productSynchronizationURL>/rest/service/deleteRecords",
  "name": "Delete Existing Records",
  "method": "POST",
  "request": {
    "pathParameters": [],
    "queryParameters": [],
    "headerParameters": [
      {
        "kind": "required",
        "name": "Content-Type",
        "type": "String",
        "description": "The content type for the request. Please set this to application/xml. "
      }
    ],
    "bodyDataParameters": [
      {
        "kind": "required",
        "name": "data-raw",
        "type": "string",
        "description": "The xml string for submitting record data. "
      }
    ],
    "formDataParameters": []
  },
  "results": {
    "languages": [
      {
        "id": "gh1drPGG88hpmPjQCpg6D",
        "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<message>\n  <status>SUCCESS</status>\n  <msg>1 record is marked for DELETION</msg>\n</message>",
        "language": "200",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "gh1drPGG88hpmPjQCpg6D"
  },
  "examples": {
    "languages": [
      {
        "id": "Tqeg_tAzlX1Uewf-czPEm",
        "code": "curl --location --request POST 'https://<productSynchronizationURL>/rest/service/deleteRecords' \\\n--header 'Content-Type: application/xml' \\\n--data-raw '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<request>\n    <sessionId>Your-Session-ID</sessionId>\n    <records>\n        <record>\n            <pairs>\n                <!-- IDs -->\n                <pair>\n                    <key>id</key>\n                    <value>123-ABC</value>\n                </pair>\n            </pairs>\n        </record>\n    </records>\n</request>'",
        "language": "curl",
        "customLabel": ""
      }
    ],
    "selectedLanguageId": "Tqeg_tAzlX1Uewf-czPEm"
  },
  "description": "The end-point is used for adding new records to index. ",
  "currentNewParameter": {
    "label": "Body Parameter",
    "value": "bodyDataParameters"
  },
  "autoGeneratedAnchorSlug": "delete-existing-records",
  "legacyHash": "q45uqTFCM5lfilfcjx_zC"
}
```
:::


[title] Examples
[path] JSON API/

Let's delve into some scenarios to better understand how to utilize the API for different purposes

[space] Klevu Magento v4 (/klevu-magento-v4)

[title] Products
[path] Indexing/Entities/


[title] Updating KlevuSettings
[path] Frontend/Theme JS/

`KlevuSettings` is an object of data passed to the Javascript function `klevu()`. These settings determine how Klevu Theme JS is configured. Theme JS configuration documentation can be found here [https://docs.klevu.com/template-js/configuration](https://docs.klevu.com/template-js/configuration).

## How Klevu Settings is Generated

The `klevuSettings` object is generated from a combination of 2 sources.

1\) The `Klevu\Frontend\Service\KlevuSettingsBuilder` which generates an array of settings via `di.xml`, with each module injecting its own settings.
e.g.

:::CodeblockTabs
Klevu/Frontend/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="global" xsi:type="array">
                <item name="apiKey" xsi:type="object">Klevu\Frontend\Service\Provider\ApiKeyProvider</item>
                <item name="language" xsi:type="object">Klevu\Frontend\Service\Provider\LanguageProvider</item>
            </item>
        </argument>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_integrated"
                  xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
        </argument>
    </arguments>
</type>

```
:::

2\) `Klevu\Frontend\Service\CustomSettingsBuilder` which generates data from the Custom Jsv2 Settings settings in the admin.

They are then combined with any setting from `CustomSettingsBuilder` overriding `KlevuSettingsBuilder`

***

## **How KlevuSettings Is Added to head and Passed to Klevu**

Klevu Jsv2 settings are added to your page `<head>` via layout xml here `module-m2-frontend/view/frontend/layout/default_head_blocks.xml`.
Specifically in block `Klevu_Frontend.js_settings` which adds 2 empty contain blocks so you can inject your own code before and after `klevu(klevuSettings)`.

The template that generates the settings is `module-m2-frontend/view/frontend/templates/html/head/js_settings.phtml`.

:::CodeblockTabs
module-m2-frontend/view/frontend/templates/html/head/js\_settings.phtml

```php
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript', 'id' => 'klevu_settings'],
    content: "\nlet klevuSettings = " . $klevuSettings . "\n",
    textContent: false,
) ?>

<?php if (!$viewModel->isSettingsGenerationError()): ?>
    <?php
    /**
     * Inject javascript into klevu_frontend.init_before
     *  to make changes to klevuSettings before passing to klevu()
     */
    ?>
    <?= $block->getChildHtml('klevu_frontend.init_before') ?>

    <?= $secureRenderer->renderTag(
        tagName: 'script',
        attributes: ['type' => 'text/javascript', 'id' => 'klevu_init'],
        content: "\nif(typeof klevuSettings !== 'undefined'){klevu(klevuSettings);}\n",
        textContent: false,
    ) ?>
    ...
```
:::

***

## Making Changes to the KlevuSettings Object

There are 3 ways to make changes to this object:

- [Set the value in the admin](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - does not change based on any business logic.
  - does not depend on any frontend element.
- [Set the value via your theme](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - is different depending on the theme (you use multiple themes in your store).
  - depends on an element on the frontend of your store that you can access via javascript.
- [Set the value via a custom module](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - depends on values stored in your database.
  - depends on more complex business logic.
  - depends on an element on the frontend of your store that you can access via javascript, you have multiple themes on your site and you need to apply the change to them all.

In reality you will likely use a combination of all 3, some set in the admin, some set in theme  or module templates that may use a ViewModel defined in your customer module.

### Adding Klevu Theme Settings Via Admin

***JSv2 settings NOT found in Stores > Configuration > Klevu Section***

Magento already has a setting for these, so we’re using the existing settings rather than duplicating them and causing potential confusion.

- Minimum characters used in search, `Stores > Configuration > Catalog > Catalog > Search > Minimal Query Length`
- Maximum characters used in search, `Stores > Configuration > Catalog > Catalog > Search > Maximum Query Length`
- Language, `Stores > Configuration > General > Locale Options > Locale`

***JSv2 settings in Stores > Configuration > Klevu Section***

**All JSv2 settings in config can be overwritten by using&#x20;**`Stores > Configuration > Klevu > Developer Settings > Frontend > Custom JSv2 Settings`**.**
e.g. if you need to defer the powerUp of the SRLP you can do that here. Set path = powerUp.landing, type=boolean, value=false.

A list of available settings can be found here [https://docs.klevu.com/template-js/configuration](https://docs.klevu.com/template-js/configuration)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/fw5Yvq2nsjQFKABSF8LrN_screenshot-2023-08-14-at-092507.png "Custom JSv2 Settings")

There are 2 settings we have given their own fields within `Stores > Configuration > Klevu > Developer Settings > Frontend`. They are

- Search Box Selector: The id, class, or handle used to bind the search input field. This is equivalent to setting `search.searchBoxSelector` in Custom Jsv2 Options.
- Search Query Parameter: The query parameter appended to the SRLP URL. This is equivalent to setting `url.queryParam` in Custom Jsv2 Options.

:::hint{type="info"}
Note: Any values set in Custom JSv2 Settings will override values set in `di.xml`
:::

:::hint{type="info"}
After changing any configuration settings, please remember to clear the Config cache.
:::

***

### Adding Klevu Theme Settings Via Theme

[Magento theme structure documentation](https://developer.adobe.com/commerce/frontend-core/guide/themes/structure/).

Sometimes setting these values via the admin is not an option.
You may need to:

- use Javascript to get an element from the page
- have different settings for different themes within the same store.

**Change KlevuSettings Before They are Passed to klevu()**

1. In your theme create a module Klevu\_Frontend, `app/code/design/frontend/Vendor/theme/Klevu_Frontend`
2. Create a layout file to add your blocks to our contain `klevu_frontend.init_before`
   `app/code/design/frontend/Vendor/theme/Klevu_Frontend/layout/default_head_blocks.xml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/layout/default\_head\_blocks.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="klevu_frontend.init_before">
            <block name="Vendor_Theme.klevu.init_before"
                   template="Klevu_Frontend::klevu/init_before.phtml"
                   before="-"/>
        </referenceContainer>
    </body>
</page>
```
:::

3\. Create the template file that will contain your customisations
`app/code/design/frontend/Vendor/theme/Klevu_Frontend/templates/klevu/init_before.phtml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/templates/klevu/init\_before.phtml

```php
<?php

use Magento\Framework\View\Helper\SecureHtmlRenderer;

/**
 * @var SecureHtmlRenderer $secureRenderer
 */

/** add your customisation e.g */
$scriptString = "
    klevu.setObjectPath(
        klevuSettings, // the object of settings we wish to amend
        'search.showQuickOnEnter', // the path in the object we wish to add/amend
        klevu.toBoolean(true) // the value to set
    );
";
?>

<?php /** Render the script tag */ ?>
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript'],
    content: $scriptString,
    textContent: false
) ?>

```
:::

***

### Adding Klevu Theme Settings Via A Custom Module

Note the example below we have used Module Vendor\_Module.
[Magento module creation documentation](https://experienceleague.adobe.com/en/docs/commerce-learn/tutorials/backend-development/create-module).

To add a new setting to `klevuSettings` before the object is output to the page you can add to the `KlevuSettingsBuilder` via frontend `di.xml`.
It is possible to set `boolean`, `const`, `number` and `string` in the XML, though these can also be set in the admin.

:::hint{type="warning"}
Note: Any values set in [Custom JSv2 Settings](https://docs.klevu.com/klevu-magento-v4/updating-klevusettings#sX4hi) will override values set here via `di.xml`
:::

`Vendor/Module/etc/di.xml`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="search" xsi:type="array">
                <item name="searchBoxTarget" xsi:type="boolean">true</item>
                <item name="maxChars" xsi:type="number">5</item>
                <item name="documentClickPreventSelector" xsi:type="string">#someId</item>
            </item>
            <item name="url" xsi:type="array">
                <item name="queryParam" xsi:type="string">queryParam</item>
            </item>
        </argument>
    </arguments>
</type>
```
:::

`<argument name="klevuSettings" xsi:type="array">` contains all the data output as `klevuSettings`.
The names of the items make up the paths in `klevuSettings`.
The generated output of the above XML would be

```javascript
klevuSettings = {
    search: {
        searchBoxTarget: true,
        maxChars: 5,
        documentClickPreventSelector: "#someId"
    },
    url : {
        queryParam: "queryParam"
    }
};
```

More interesting though is the ability to pass an instance of `Klevu\FrontendApi\Service\Provider\SettingsProviderInterface`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="search" xsi:type="array">
                <item name="searchBoxSelector" xsi:type="object">Vendor\Module\Service\Provider\YourProvider</item>
            </item>
        </argument>
    </arguments>
</type>
```
:::

If the provider returns a value from `core_config_data` you can create a `virtualType` for `Klevu\Frontend\Service\Provider\SettingsProvider` and pass it the path and return type.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\YourProvider"
    type="Klevu\Frontend\Service\Provider\SettingsProvider">
    <arguments>
        <argument name="path" xsi:type="string">path/to_your/setting</argument>
        <argument name="returnType"
                  xsi:type="const">Klevu\Frontend\Block\Adminhtml\Form\Field\TypeColumn::TYPE_VALUE_STRING</argument>
    </arguments>
</virtualType>
```
:::

Valid `returnType` are `TYPE_VALUE_BOOLEAN`, `TYPE_VALUE_INTEGER`, and `TYPE_VALUE_STRING`.

If your provider requires more business logic, create the class that implements `Klevu\FrontendApi\Service\Provider\SettingsProviderInterface`.

:::CodeblockTabs
Vendor/Module/Service/Provider/YourProvider.php

```php
<?php

declare(strict_types=1);

namespace Vendor\Module\Service\Provider;

use Klevu\FrontendApi\Service\Provider\SettingsProviderInterface;

class YourProvider implements SettingsProviderInterface
{
    public function get(): string|int|bool|null
    {
        // add your logic
    }
}
```
:::

Settings Provider Examples

- `Klevu\Frontend\Service\Provider\ApiKeyProvider`
- `Klevu\FrontendSearch\Service\Provider\LandingUrlProvider`
- `Klevu\FrontendCategoryNavigation\Service\Provider\LandingInfiniteScrollOffsetProvider`

:::hint{type="info"}
Your provider may throw an exception of type `Klevu\Frontend\Exception\OutputDisabledException`.
This will prevent the setting from being added to the output.
:::




[title] Pipelines
[path] Indexing/Entities/Sync/

If an attribute has been registered with Klevu for indexing that does not mean that the entity data from that attribute is automatically sent to Klevu. It means it can be sent to Klevu.&#x20;

Entity data indexed to Klevu is defined in the indexing pipelines YAML files.&#x20;
These files can either be:

- auto-generated via the product attribute setting `Automatically Generate Pipeline Configuration For` see [Attribute Admin Settings ](https://docs.klevu.com/klevu-magento-v4/attributes#vOPPl)
- manually created if the auto-generated code is not desirable, see [Pipeline Customisation](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation).

The auto-generated pipeline YAML files can be found in `var/klevu/indexing/pipeline/`.&#x20;

***

## PHP-SDK, Pipelines & Magento Overview

Klevu indexing uses [Klevu’s Data Indexing JSON API](https://docs.klevu.com/indexing-apis/overview). Klevu has developed a [PHP-SDK](https://github.com/klevu/php-sdk) to assist developers with integrating Klevu indexing into any PHP Platform. This PHP-SDK is used to index data to Klevu in these Magento modules.

Klevu has also developed [PHP-Pipelines](https://github.com/klevu/php-pipelines), these are generic PHP pipelines that can be used for any purpose and are independent of Magento and the PHP-SDK.&#x20;

These 2 modules are brought together via [php-sdk-pipelines](https://github.com/klevu/php-sdk-pipelines), adding PHP-SDK functionality into the pipelines.

There is a 4th module, [module-m2-pipelines](https://github.com/klevu/module-m2-pipelines) which integrates these new components into Magento. This handles dependency injection and adds some Magento context into the pipelines.

***

## Types of Pipeline

### Create Record Pipeline: `Pipeline\CreateRecord`

Create and return a new object.
Example:
Create an object with keys `id` and `type`

```yaml
pipeline: Pipeline\CreateRecord
stages:
  id:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getEntityId()
      transformations: ToString
  type:
    pipeline: Stage\StaticValue
    args:
      value: "KLEVU_PRODUCT"
```

Output:

```json
{
    "id": "123",
    "type": "KLEVU_PRODUCT"
}
```

### Fallback Pipeline: Pipeline\Fallback

If any validation exception `ValidationExceptionInterface` is thrown, catch it and move on to the next stage, otherwise return the output from this stage.

Example:&#x20;

- Get the product type,&#x20;
- Validate that the type is “bundle”
  - If valid include this file `product/bundle.yml`
  - If not valid move to the next stage which will include this file `product/default.yml`

```yaml
bundleProduct:
  stages:
    -
      pipeline: Stage\Extract
      args:
        extraction: currentProduct::getTypeId()
    -
      pipeline: Stage\Validate
      args:
        validation: IsEqualTo("bundle")
    -
      import: Klevu_IndexingProducts::etc/pipeline/product/bundle.yml
default:
  stages:
    -
      import: Klevu_IndexingProducts::etc/pipeline/product/default.yml
```

Note: the stage names have been removed from this example to make it easier to read

### Iterate Pipeline: Pipeline\Iterate

Loop over the provided records.

Example:
Iterate over all records provided into the pipeline

```yaml
stages:
  iterateIndexingRecords:
    pipeline: Pipeline\Iterate
    stages:
     -
        ...
```

or get all customer groups, iterate over then, setting the current customer group at the start of each loop

```yaml
getCustomerGroups:
  pipeline: Stage\Extract
  args:
    extraction: store::getForCurrentStore().customer_groups
    transformations: ToString
IterateCustomerGroups:
  pipeline: Pipeline\Iterate # LOOP OVER ALL CUSTOMER GROUPS
  stages:
    SetCustomerGroupId:
      pipeline: Stage\SetCustomerGroupId
    ...
```

***

## Pipeline Stages

### Static Value

Add a value to the output.

Example:

```yaml
pipeline: Pipeline\CreateRecord
stages:
  type:
    pipeline: Stage\StaticValue
    args:
      value: "KLEVU_PRODUCT"
    
```

Output:

```json
{
    "type": "KLEVU_PRODUCT"
}
```

### Extract

Get the value from the extraction and pass it to the next stage
Example:

```yaml
pipeline: Pipeline\CreateRecord
stages:
  id:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getEntityId()
```

Output:

```json
{
    "id": 123
}
```

### Transform

Transform the provided value using one or multiple transformers.
Example:

```yaml
pipeline: Pipeline\CreateRecord
stages:
  id:
    - pipeline: Stage\Extract
      args:
        extraction: currentProduct::getEntityId()
    - pipeline: Stage\Transform 
      args:
        transformation: ToString|Trim|Prepend("ID: ")
```

Output:

```json
{
    "id": "ID: 123"
}
```

Alternatively, transformations can be passed into extractions, skipping the need to add an extra stage.

Example:

```yaml
pipeline: Pipeline\CreateRecord
stages:
  name:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getName()
      transformations: 
        - Trim
        - Append(" - ", $currentProduct::getManufacturer())
```

Output:

```json
{
    "name": "Test Product - Brand Name"
}
```

### Validate

Example:

```yaml
- pipeline: Stage\Extract
  args:
    extraction: currentProduct::getKlevuImage()
- pipeline: Stage\Validate
  args:
    validation: IsNotEqualTo("no_selection")|IsNotEmpty

```

If validation fails an exception of type `Klevu\Pipelines\Exception\ValidationExceptionInterface` will be thrown. Fallback pipelines will catch this an proceed to the next stage.
See `module-m2-indexing-products/etc/pipeline/attributes/images.yml`

### Register Context

Register a variable to be used elsewhere in the pipeline.

Example:
Extract the current product and then register the context as currentProduct

```yaml
extractProduct:
  pipeline: Stage\Extract
  args:
    extraction: currentIndexingRecord::getEntity()
registerProduct:
  pipeline: Stage\RegisterContext
  args:
    contextKey: "currentProduct"
```

Then later in the pipeline (possibly in another file, even another module) the context can be used.

```yaml
pipeline: Pipeline\CreateRecord
stages:
  default:
    stages:
      -
        pipeline: Stage\Extract
        args:
          extraction: currentProduct::getName()
          transformations: EscapeHtml
```

Output:

```json
{
    default: 'Product Name'
}
```

### Log

Log the current context.&#x20;

Example:&#x20;
`module-m2-indexing/etc/pipeline/process-batch-payload.yml`
Take whatever the current context is (the output from the previous operation) and log it along with the message “Chunked payload” at log level “debug”.

```yaml
stages:
  log:
    pipeline: Indexing\Stage\Log
    args:
      message: "Chunked payload"
      level: debug
```

Output (formatted to make it more readable):

```none
report.DEBUG: Chunked payload {
    "identifier":"processPayload.processRecords.iterate.log",
    "payload":[
        {"id":"47","type":"KLEVU_PRODUCT","relations":{"categories":{"values":["categoryid_15","categoryid_36","categoryid_2","categoryid_12"]}},"attributes":{"name":{"default":"Chaz Kangeroo Hoodie-XS-Black"},"sku":"MH01-XS-Black","images":[{"url":"https://magento.test/media/catalog/product/cache/7fe2def9e1d815fff5838a5b86f54f8b/m/h/mh01-black_main_1.jpg","type":"default","width":800,"height":800}],"prices":[{"amount":52.0,"type":"defaultPrice","currency":"USD"},{"amount":52.0,"type":"salePrice","currency":"USD"}],"url":"https://magento.test/catalog/product/view/id/47/s/chaz-kangeroo-hoodie-xs-black/","inStock":true,"shortDescription":{"default":null},"description":{"default":"Ideal for cold-weather training or work outdoors, the Chaz Hoodie promises superior warmth with every wear. Thick material blocks out the wind as ribbed cuffs and bottom band seal in body heat. &amp;bull; Two-tone gray heather hoodie.&amp;bull; Drawstring-adjustable hood. &amp;bull; Machine wash/dry."},"tags":[],"visibility":[],"rating":4.2,"ratingCount":321}},
        {"id":"2051-2053","type":"KLEVU_PRODUCT","relations":{"parentProduct":{"values":["2051"]}},"attributes":{"sku":"Configurable product link test-Orange-1","images":null,"type":"default","width":800,"height":800}],"prices":[{"amount":45.0,"type":"defaultPrice","currency":"USD"},{"amount":45.0,"type":"salePrice","currency":"USD"}],"url":"https://magento.test/configurable-product-link-test.html","inStock":true,"shortDescription":{"default":null},"description":{"default":null},"rating":4.7,"ratingCount":123}}
    ]
} []
```


[title] Integration
[path] Installation & Integration/New Installation of v4.x/

To integrate your Klevu API keys with your Magento store.

- Login to Magento admin
- Navigate to `Stores > Configuration > Klevu > Integration`

### Step 1: Enter your Auth Keys

- Select the store from the table to integrate and click `Integrate Store` in the actions column.
- A modal will open containing the integration form.
- Enter the API key and Auth Key provided in KMC and click `Check API Keys`
- An API call will check if the provided keys:
  - are for an enabled account,
  - are registered for a Magento store,
  - are set up for JSON indexing and not XML indexing

:::hint{type="info"}
If this validation fails, error messages will be displayed at the top of the modal with more information.
:::

### Step 2: Save the Auth Keys

- Account Details will be displayed for this account. Ensure this is the account you wish to integrate with this store. If so, click `Save API Keys`
  This step may take a moment while. There are 3 processes running:
  - **Trigger Attribute Discovery** - find all your attributes, calculate if they need to be registered with Klevu and populate the `klexu_indexing_attribute` table.
  - **Trigger Attribute Registration** - registering those attributes, via API, that need to be registered with Klevu to enable entity sync.
  - **Queue Entity Discovery** - add a cron task to find all your entities, calculate if they need to be indexed with Klevu and populate the `klexu_indexing_entity` table. This step is triggered via cron rather than synchronously as it can take some time depending on how many entities (categories, CMS pages and products) your store has.
- At this point the integration is complete. The remaining steps guide you where to find certain settings within the Klevu plugin related to frontend, analytics and indexing. These steps can be skipped by closing the modal if you desire.&#x20;

:::hint{type="info"}
Note: The discovery and indexing of entities is not triggered during the integration, but is handled via the cron. In a production environment the cron **must** be running, however, while testing the cron may not be running. Entity indexing can also be triggered via CLI (see [Indexing - Entities](https://docs.klevu.com/klevu-magento-v4/entities)).
:::

:::hint{type="info"}
As with all cron tasks added by version v4.x of the Klevu integration, entity discovery and sync cron tasks use the dedicated `klevu` group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::


[title] Custom Product Types
[path] Indexing/Entities/Products/

Product types are injected via this virtualType `Klevu\IndexingProducts\Service\Provider\EntityProviderProvider` in the indexing products module `etc/di.xml`

:::CodeblockTabs
magento2-plugin/module-m2-indexing-products/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\EntityProviderProvider"
             type="Klevu\Indexing\Service\Provider\EntityProviderProvider">
    <arguments>
        <argument name="entityProviders" xsi:type="array">
            <item name="simple"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Simple</item>
            <item name="virtual"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Virtual</item>
            <item name="downloadable"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Downloadable</item>
            <item name="grouped"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Grouped</item>
            <item name="bundle"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Bundle</item>
            <item name="configurable"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Configurable</item>
            <item name="configurable_variants"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\ConfigurableVariants</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Merchants can add to this `EntityProviderProvider`&#x20;
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\EntityProviderProvider">
    <arguments>
        <argument name="entityProviders" xsi:type="array">
            <item name="custom_type"
                  xsi:type="object">Vendor\Module\Service\Provider\ProductEntityProvider\CustomTypeProvider</item>
        </argument>
    </arguments>
</virtualType>
```
:::

There are 2 ways in which this `CustomTypeProvider` can be generated.

1\. (Recommended) Use `virtualTypes`, as the Klevu module does, and pass your custom `productType`
e.g

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<!-- Virtual type for ProductEntityProvider -->
<virtualType name="Vendor\Module\Service\Provider\ProductEntityProvider\CustomTypeProvider"
             type="Klevu\IndexingProducts\Service\Provider\ProductEntityProvider">
    <arguments>
        <argument name="productEntityCollection"
                  xsi:type="object">Vendor\Module\Service\Provider\Discovery\ProductEntityCollection\CustomType</argument>
    </arguments>
</virtualType>

<!-- Virtual type for the ProductEntityCollection used above --> 
<!-- This will return all product of type "custom_type" -->
<virtualType name="Vendor\Module\Service\Provider\Discovery\ProductEntityCollection\CustomType"
             type="Klevu\IndexingProducts\Service\Provider\Discovery\ProductEntityCollection">
    <arguments>
        <argument name="productType" xsi:type="string">custom_type</argument>
    </arguments>
</virtualType>
```
:::

2\. Create a class. This is recommended if you need to filter the returned products on more than the product type.
The provider must implement `Klevu\IndexingApi\Service\Provider\EntityProviderInterface`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\ProductEntityProvider\CustomTypeProvider"
             type="Klevu\IndexingProducts\Service\Provider\ProductEntityProvider">
    <arguments>
        <argument name="productEntityCollection"
                  xsi:type="object">Vendor\Module\Service\Provider\Discovery\ProductEntityCollection\CustomType</argument>
    </arguments>
</virtualType>

```
:::

Create the provider

:::CodeblockTabs
Vendor/Module/Service/Provider/Discovery/ProductEntityCollection/CustomTypeProvider.php

```php
<?php

namespace Vendor\Module\Service\Provider\Discovery\ProductEntityCollection;

use Klevu\IndexingApi\Service\Provider\EntityProviderInterface;

class CustomType implements EntityProviderInterface
{
    /**
     * ProductCustomTypeEntityCollection $productCustomTypeEntityCollection
     */
    public function __construct(
        ProductCustomTypeEntityCollection $productCustomTypeEntityCollection,
    ) {
        $this->productCustomTypeEntityCollection = $productCustomTypeEntityCollection;
    }
    
    /**
     * @param StoreInterface|null $store
     * @param int[]|null $entityIds
     *
     * @return ProductCollection
     */
    public function get(
        ?StoreInterface $store = null, 
        ?array $entityIds = [],
    ): ?\Generator {
        $collection = $this->productCustomTypeEntityCollection->get(
            store: $store, 
            entityIds: $entityIds,
        );
        foreach ($collection as $product) {
            yield $product;
        }
    }
}
```
:::

Here `ProductCustomTypeEntityCollection` is a class that returns a collection of the custom product type.


[title] Cron - Quick Reference
[path] Indexing/

Klevu adds multiple cron jobs to manage the registration of attributes and the indexing of entity data.

:::hint{type="info"}
All cron tasks added by version 4.x of the Klevu integration use the dedicated `klevu` cron group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

In a non-production environment, you may not be running the cron.&#x20;
You can trigger only the Klevu cron jobs using the following command.

```shell
bin/magento cron:run --group klevu
```

## Attribute Discovery

Runs once a day as a fall back in case the addition or removal of any attributes was missed by our event observers and plugins.

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_discover_attributes"
     instance="Klevu\Indexing\Cron\DiscoverAttributes"
     method="execute">
    <schedule>52 1 * * *</schedule>
</job>
```
:::

## Attribute Sync

Runs every 10 minutes (by default, the schedule is configurable in the admin)

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_attributes"
     instance="Klevu\Indexing\Cron\SyncAttributes"
     method="execute">
    <config_path>klevu/indexing/attribute_cron_expr</config_path>
</job
```
:::

## Entity Discovery

Runs once a day as a fall back in case the addition or removal of any entities was missed by our event observers and plugins.

:::CodeblockTabs
&#x20;module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_discover_entities"
     instance="Klevu\Indexing\Cron\DiscoverEntities"
     method="execute">
    <schedule>0 2 * * *</schedule>
</job>
```
:::

## Entity Sync

Runs every 30 minutes (by default, the schedule is configurable in the admin)

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_entities"
     instance="Klevu\Indexing\Cron\SyncEntities"
     method="execute">
    <config_path>klevu/indexing/entity_cron_expr</config_path>
</job>
```
:::

## Entity Sync History Consolidation

Runs once a day to consolidate the days sync history into one database entry.

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_history_consolidation"
     instance="Klevu\Indexing\Cron\SyncHistoryConsolidation"
     method="execute">
    <schedule>2 0 * * *</schedule>
</job>
```
:::

## Entity Sync History Consolidation Clean

Runs once a day to remove sync history older than x days.&#x20;

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_history_consolidation_clean"
   instance="Klevu\Indexing\Cron\SyncHistoryConsolidationClean"
   method="execute">
  <schedule>10 0 * * *</schedule>
</job>>
```
:::

Number of days defaults to 7 and is configured in the admin `klevu/indexing/remove_indexing_history_after_days`&#x20;

[title] Updating Klevu Modules
[path] Installation & Integration/

All updates should be completed and tested in a non-production environment.

## Non-Production Environment

### Step 1 - Update v4.x packages

Update the modules via composer.&#x20;

```javascript
composer update "klevu/*"
```

### Step 2 - Update Magento

Enable modules, update the database, compile code, generate static content and clear caches.

```shell
bin/magento module:status | grep Klevu_ | grep -v List | grep -v None | grep -v -e '^$'| xargs php bin/magento module:enable
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy
bin/magento cache:flush
```

### Step 3 - Test

Ensure everything is working as expected in a non-production environment.

## Production Environment

**Follow your usual deployment processes**, the steps in this section are provided as a guide only (assumes `composer.lock` file is committed to your git repository).

- Enable Maintenance Mode `bin/magento maintenance:enable`
- Install the modules via `composer install`
- Enable all Klevu modules `bin/magento module:status | grep Klevu_ | grep -v List | grep -v None | grep -v -e '^$'| xargs php bin/magento module:enable`
- Upgrade Magento `bin/magento setup:upgrade`
- Compile code `bin/magento setup:di:compile`
- Deploy static content `bin/magento setup:static-content:deploy`
- Clean caches `bin/magento cache:clean`
- Disable Maintenance Mode `bin/magento maintenance:disable`

****


[title] CLI - Quick Reference
[path] Indexing/

Summary of Klevu Indexing CLI Commands

## Attribute Discovery

`klevu:indexing:attribute-discovery`

The discovery can also be triggered via CLI and has 2 optional parameters&#x20;

- `api-keys` - \[optional] comma-separated list of API keys to run discovery for
- `attribute-types` - \[optional] comma-separated list of  attribute types to run discovery for, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

```shell
bin/magento klevu:indexing:attribute-discovery \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key"
```

## Attribute Update&#x20;

`klevu:indexing:attribute-update`

The update can be triggered via CLI and has 1 required parameter and 2 optional parameters&#x20;

- `attribute-ids` - comma-separated list of attribute IDs to update
- `api-keys` - \[optional] comma-separated list of API keys to update
- `attribute-types` - \[optional] comma-separated list of  attribute types to update, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

```shell
bin/magento klevu:indexing:attribute-update \
    --attribute-ids="1,2,3" \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" 
```

## Attribute Sync

`klevu:indexing:attribute-sync`

The sync can be triggered via CLI and has 2 optional parameters&#x20;

- `api-keys` - \[optional] comma-separated list of API keys to sync
- `attribute-types` - \[optional] comma-separated list of attribute types to sync, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

Increasing the verbosity of the command will give you more information using `-v`, `-vv`, or `-vvv`

```shell
bin/magento klevu:indexing:attribute-sync \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" \
    -vvv
```

***

## Entity Discovery

`klevu:indexing:entity-discovery`

The discovery can be triggered via CLI and has 2 optional parameters

- `api-keys` - \[optional] comma-separated list of API keys to run discovery for
- `entity-types` - \[optional] comma-separated list of entity types to run discovery for,
  options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`
  - `KLEVU_CMS`

```shell
bin/magento klevu:indexing:entity-discovery \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key"
```

## Entity Update

`klevu:indexing:entity-update`

The update can be triggered via CLI and has 1 required parameter and 2 optional parameters

- `entity-ids` - a comma-separated list of entity IDs to update
- `api-keys` - \[optional] comma-separated list of API keys to update
- `entity-types` - \[optional] comma-separated list of entity types to update,
  options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`

```shell
bin/magento klevu:indexing:entity-update \
    --entity-ids="1,2,3" \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key"
```

## Entity Sync

`klevu:indexing:entity-sync`

The sync can be triggered via CLI and has 2 optional parameters

- `api-keys` - \[optional] comma-separated list of API keys to update
- `entity-types` - \[optional] comma-separated list of entity types to sync,
  &#x20;options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`
  - `KLEVU_CMS`

Increasing the verbosity of the command will give you more information using `-v`, `-vv`, or `-vvv`

```shell
bin/magento klevu:indexing:entity-sync \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" \
    -vvv
```


[title] Frontend
[path] /


[title] User Interface
[path] Analytics/

The Order Analytics module makes changes to two locations in the Magento backend in order to add sync operation information to order records.

## Orders Grid

A new column - **Klevu Sync Status** - has been added to the Sales > Orders grid containing the current status of the order record. This field can be toggled via the Columns menu and reordered using drag-and-drop.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/Y0k9y0SnHEokexHHbHDSu_image-20240328-154950.png "Sales Orders Grid")

Klevu Sync Status can also be used to filter and sort the orders grid.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/RfCAJL60omVF1DRhJ_gGX_image-20240328-163939.png "Filtered Sales Order Grid")

## Order View

A new tab has been added to the View Order screen, called Klevu Order Sync History. Within this section you can view the current status of the order, along with the number of times a sync has been attempted. There is also an output of all sync history items, showing when and via what method actions were performed.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/dcS2xRBI5qSmzXXr8g7Ao_image-20240328-164454.png "Sales Order View")


[title] Categories
[path] Indexing/Entities/

## Anchor Categories

Out of the box, the Klevu plugin respects the `is_anchor` category setting.
To change this behaviour and ignore anchor categories you can add an before-plugin on `ParentAnchorCategoryIdProvider` and return an empty array.
Setting `categoryIds` param as an empty array will return an empty array skipping any extra database calls.

```xml
<type name="Klevu\IndexingProducts\Service\Provider\Catalog\ParentAnchorCategoryIdProvider">
  <plugin name="Vendor_Module::ParentAnchorCategoryIdProvider"
          type="Vendor\Module\Plugin\Service\Provider\Catalog\ParentAnchorCategoryIdProviderPlugin"/>
</type>
```

Create the Plugin class

:::CodeblockTabs
Vendor/Module/Plugin/Service/Provider/Catalog/ParentAnchorCategoryIdProviderPlugin.php

```php
<?php

namespace Vendor\Module\Plugin\Service\Provider\Catalog;

use Klevu\IndexingApi\Service\Provider\Catalog\ParentAnchorCategoryIdProviderInterface;

class ParentAnchorCategoryIdProviderPlugin
{
    /**
     * @param ParentAnchorCategoryIdProviderInterface $subject
     * @param int[] $categoryIds
     *
     * @return int[]
     */
    public function beforeGet(
        ParentAnchorCategoryIdProviderInterface $subject,
        array $categoryIds,
    ): array {
        return [[]];
    }
}
```
:::

## Custom Attributes Name Prefix

As Magento has separate attributes for products and categories and these attributes can have the same name. Klevu does not differentiate attributes between types and therefore a name clash could occur with category and product attributes overwritting each other. To mitigate this we have added a prefix to any custom category attributes. By default this prefix is set to `cat__`.

:::CodeblockTabs
module-m2-indexing-categories/etc/di.xml

```xml
<virtualType name="Klevu\IndexingCategories\Service\Mapper\MagentoToKlevuAttributeMapper"
             type="Klevu\Indexing\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="entityType"
                  xsi:type="const">Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE</argument>
        
        <!-- CATEGORY ATTRIBUTE PREFIX -->
        <argument name="prefix" xsi:type="string">cat__</argument>
        
        <argument name="attributeMapping" xsi:type="array">
            <item name="path" xsi:type="string">categoryPath</item>
            <item name="url_key" xsi:type="string">url</item>
        </argument>
    </arguments>
</virtualType>
```
:::

You are free to change this prefix.&#x20;
Note: it is limited to underscores and alphanumeric characters only.
If you change the prefix you’ll also need to ensure that any `cat__attribute_code` references in your pipeline YMAL files and/or frontend search requests are updated with the new prefix.

```xml
<virtualType name="Klevu\IndexingCategories\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="prefix" xsi:type="string">prefix_</argument>
    </arguments>
</virtualType>
```


[title] Is Enabled Determiner
[path] Frontend/

`Klevu/Frontend/Service/IsEnabledDeterminer.php` determines if we should output to the frontend.

We pass a multi-dimensional array of `Klevu\FrontendApi\Service\IsEnabledCondition\IsEnabledConditionInterface` to the determiner.

### And Condition

Any condition at the top level of the array is treated as an `AND` condition.
e.g.

:::CodeblockTabs
Klevu/Frontend/etc/di.xml

```xml
<type name="Klevu\Frontend\ViewModel\CustomerGroupSuffix">
    <arguments>
		<argument name="isEnabledConditions" xsi:type="array">
		    <item name="klevu_integrated"
		          xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
		    <item name="klevu_customer_group_price_enabled"
		          xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsCustomerGroupPriceEnabledCondition</item>
		</argument>
	</arguments>
</type>

```
:::

Here we only output the customer price group suffix if **both** this store is integrated with Klevu **and** Customer Group Pricing is enabled in the admin.

### Or Condition

Any condition at any lower level of the array is treated as an `OR` condition.
e.g.

:::CodeblockTabs
Klevu/FrontendSearch/etc/di.xml

```xml
<type name="Klevu\Frontend\ViewModel\CurrencyConversion">
    <arguments>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_modules_enabled" xsi:type="array">
                <item name="klevu_quick_enabled"
                      xsi:type="object">Klevu\FrontendSearch\Service\IsEnabledCondition\IsQuickSearchEnabledCondition</item>
                <item name="klevu_srlp_enabled"
                      xsi:type="object">Klevu\FrontendSearch\Service\IsEnabledCondition\IsSrlpEnabledCondition</item>
            </item>
        </argument>
    </arguments>
</type>

```
:::

Here we output the currency conversion javascript if **either** quick search **or** search results landing page are enabled as they both require currency conversions.

### Combining And & OR

As each module injects its own configuration that consolidated CurrencyConversion XML will look like this

```xml
<type name="Klevu\Frontend\ViewModel\CurrencyConversion">
    <arguments>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_integrated" xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
            <item name="klevu_modules_enabled" xsi:type="array">
                <item name="klevu_catnav_enabled"
                      xsi:type="object">Klevu\FrontendCategoryNavigation\Service\IsEnabledCondition\IsCatNavEnabledCondition</item>
                <item name="klevu_recs_enabled"
                      xsi:type="object">Klevu\FrontendRecommendations\Service\IsEnabledCondition\IsRecommendationsEnabledCondition</item>
                <item name="klevu_quick_enabled"
                      xsi:type="object">Klevu\FrontendSearch\Service\IsEnabledCondition\IsQuickSearchEnabledCondition</item>
                <item name="klevu_srlp_enabled"
                      xsi:type="object">Klevu\FrontendSearch\Service\IsEnabledCondition\IsSrlpEnabledCondition</item>
            </item>
        </argument>
    </arguments>
</type>

```

Here we only output the currency conversion javascript if&#x20;
**Both**&#x20;
&#x20;   `klevu_integrated` - the store is integrated with Klevu&#x20;
**AND**&#x20;
&#x20;   `klevu_modules_enabled` - at least one of these options is enabled.
&#x20;       **Either** ****
&#x20;       `klevu_catnav_enabled` - Category Navigation is rendered with Template JS
&#x20;       **OR**&#x20;
&#x20;       `klevu_recs_enabled` - Recommendation is enabled&#x20;
&#x20;       **OR**&#xA;**&#x20;       &#x20;**`klevu_quick_enabled` - Quick Search is enabled
&#x20;       **OR**
&#x20;       `klevu_srlp_enabled` - Search Result Landing Page is rendered with Template JS

i.e. If the store is integrated and one of the options that requires currency conversion is enabled.


[title] Release Notes
[path] Klevu Module v4.x Overview/

Release notes can be found on our [Github releases page](https://github.com/klevu/module-m2-search/releases) for the metapackage module `klevu/module-m2-search`.&#x20;

These release notes will summarise the release, listing any `NEW FEATURE`, `IMPROVEMENT` or `BUGFIX` in the release as well as any composer dependency changes.

`Breaking Changes` or `Attention` will be drawn to any important issues with the release. e.g. any potential breaking changes (though we endeavour to keep those to an absolute minimum) or bugs found after release that have an impact on the release's stability.

***

## 4.4.2

Please note, version `4.4.2` contains changes to product stock and status determination used in indexing.

## Changelog

- \[FEATURE] Sync Information CLI now support KLEVU\_CATEGORY entity information
- \[FEATURE] Sync Information CLI now support KLEVU\_CMS entity information
- \[FEATURE] Ability to disable triggering entity discovery on catalog rule reindex
- \[IMPROVEMENT] Stock status update for configurable product now cascades Requires Update flag to child variants
- \[IMPROVEMENT] Transfer inventory to stock source mass action now triggers discovery for affected entities
- \[BUGFIX] Resolve logger entering infinite loop writing message in edge case scenarios
- \[BUGFIX] Resolve unhandled exception in entity sync information CLI when unknown entity type requested
- \[BUGFIX] Resolve incorrect determination of entity id in sync where identifier prefix contains multiple underscores

## 4.4.1

## Changelog

- \[IMPROVEMENT] Changes to attribute set definition now triggers entity discovery for affected entities
- \[IMPROVEMENT] Changes to product-website associations now triggers entity discovery for affected entities
- \[IMPROVEMENT] Bulk assign / unassign of Stock Sources now triggers entity discovery for affected entities
- \[BUGFIX] Product stock status now always returns false where a product is not present within requested website
- \[BUGFIX] Product stock status for complex products (Configurable, Bundle, Grouped) now always returns false where no children are present, or all are out of stock for requested store
- \[BUGFIX] Product stock status now respects requested store view when calculating using is\_available or is\_salable, rather than store view in which product was initially loaded
- \[BUGFIX] Resolve exception thrown by Process Require Updates cron where target entity has been deleted
- \[BUGFIX] Resolve exception when NULL passed to entity subtypes argument in EntityDiscoveryOrchestratorService
- \[TECHNICAL] Add missing dependencies
- \[CHORE] Miscellaneous refactoring and clean-up

## 4.4.0

Please note, version `4.4.0` contains changes to product stock and status determination used in indexing. While these should not contain breaking changes, with updates applied via configuration flags, this version should still be considered a major release and be tested accordingly before deployment.

- [Github Changelog](https://github.com/klevu/module-m2-search/releases/tag/4.4.0)
- [Detailed Release Notes](docId\:RrjmUn7irqpkZjICLlTpI)

***

## 4.2.0 - Breaking Changes

Please note version `4.2.0` contains some breaking changes.

**Analytics**

`module-m2-analytcis-order-sync/Setup/Patch/Data/MigrateLegacyOrderSyncRecords.php` constructor classes removed - See [Analytics Order Sync Pull Request](https://github.com/klevu/module-m2-analytics-order-sync/pull/7/files#diff-8ece0bc38cd68f5cf926a4497e40cfaff080ad8ef34b7d2c36c3fdf20f441d69)

**Frontend**

Classes defined in `etc/frontend/di.xml` moved to `etc/di.xml` for the following modules:

- `module-m2-frontend`,&#x20;
- `module-m2-frontend-categorynavigation`,&#x20;
- `module-m2-frontend-metadata`,&#x20;
- `module-m2-frontend-metadata-categorynavigation`,&#x20;
- `module-m2-frontend-metadata-recommendations`,&#x20;
- `module-m2-frontend-metadata-search`,&#x20;
- `module-m2-frontend-recommendations`,
- `module-m2-frontend-search`

This is to work around a core Magento issue where app emulation for the frontend, used by PageBuilder (and others), does not load the DI configuration for the frontend, but uses the global DI config. This caused PageBuilder not to render in the admin. We also saw this causes issue with Breeze.

**Indexing**

These changes are to improve performance where we have changed methods from returning `arrays` to returning `\Generators` and methods that now accept `\Generators` instead of `arrays`.&#x20;
See the [Indexing API Pull Request](https://github.com/klevu/module-m2-indexing-api/pull/9) for the methods effected by this change.

We have also made a change in the products indexing pipeline.&#x20;
`SetCustomerGroupId` stage has been removed from the pipelines and replaced with `SetCustomerGroupIdOnProduct` - see [Indexing Products Pull Request.](https://github.com/klevu/module-m2-indexing-products/pull/11/files#diff-3f16b43f9d227fcedf36bd8cc6bbed8bd9cd1849bb69783df894730f5be85cc0) This fixes the issue with Catalog Price Rules being ignored when indexing is triggered via cron.

### 4.2.0 - Post Deployment Actions

Along with the usual post deployments actions such as `bin/magento setup:upgrade` and `bin/magento setup:di:compile` please ensure you also regenerate the pipeline configuration

```shell
bin/magento klevu:indexing:configuration-overrides-regenerate
```

***


[title] New Installation
[path] Installation & Integration/


[title] Entity Sync
[path] Indexing/Entities/Custom Entity Types/

After discovering the entities, we need to sync them with Klevu by injecting `EntityIndexerService` services into the `EntitySyncOrchestratorService`. We inject a separate service for each action, i.e. `Add`, `Delete` and `Update`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Indexing\Service\EntitySyncOrchestratorService">
    <arguments>
        <argument name="entityIndexerServices" xsi:type="array">
            <item name="CUSTOM_TYPE" xsi:type="array">
                <item name="add"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Add</item>
                <item name="delete"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Delete</item>
                <item name="update"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Update</item>
            </item>
        </argument>
    </arguments>
</type>

```
:::

Now create each of the injected `EntityIndexerService`.

:::hint{type="info"}
You can create your own service classes that implement `\Klevu\IndexingApi\Service\EntityIndexerServiceInterface` and handle indexing the data with Klevu. If you choose this route please refer to the Klevu PHP-SDK documentation.

If you wish to use Klevu pipelines to index data with Klevu please continue following the example below.
:::

Create a virtual type of `Klevu\Indexing\Service\EntityIndexerService`.&#x20;
Repeat this step for `Delete` and `Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\EntityIndexerService\Add"
             type="Klevu\Indexing\Service\EntityIndexerService">
    <arguments>
        <argument name="entityIndexingRecordProvider"
                  xsi:type="object">Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider\Add</argument>
        <argument name="pipelineConfigurationFilepath"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update.yml</argument>
    </arguments>
</virtualType>
<!-- Repeat for Delete and Update -->
```
:::

Create a virtualType of `Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider` (which doesn't exist yet) to set the action to be performed.&#x20;
Repeat this step for `Delete` and `Update` actions

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider\Add"
             type="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider">
    <arguments>
        <argument name="action" xsi:type="string">Add</argument>
    </arguments>
</virtualType>
<!-- Repeat for Delete and Update -->
```
:::

Now create the missing `Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider` mentioned in the previous step. This is a virtual type of `Klevu\Indexing\Service\Provider\Sync\EntityIndexingRecordProvider`.
Pass in the same `entityProvider` we created during[ Custom Entity Types Entity Discover](https://app.archbee.com/public/PREVIEW-8cIJaE_9UAmWKNnQcRcUb/PREVIEW-kUUyybX7wBIKFjkpsneVd) section.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider"
             type="Klevu\Indexing\Service\Provider\Sync\EntityIndexingRecordProvider">
    <arguments>
        <argument name="entityProviders" xsi:type="array">
            <!-- ALREADY CREATED IN ENTITY DISCOVERY SECTION -->
            <item name="custom_type"
                  xsi:type="object">Vendor\Module\Service\Provider\CustomTypeEntityProvider</item>
        </argument>
        <argument name="indexingRecordCreatorService"
                  xsi:type="object">Vendor\Module\Service\EntityIndexingRecordCreatorService</argument>
        <argument name="entityType" xsi:type="string">CUSTOM_TYPE</argument>
    </arguments>
</virtualType>
```
:::

Create `Vendor\Module\Service\EntityIndexingRecordCreatorService` which implements `Klevu\IndexingApi\Service\EntityIndexingRecordCreatorServiceInterface`

:::CodeblockTabs
php

```php
class EntityIndexingRecordCreatorService implements EntityIndexingRecordCreatorServiceInterface
{
    public function execute(
        int $recordId,
        Actions $action,
        PageInterface|ExtensibleDataInterface $entity,
        PageInterface|ExtensibleDataInterface|null $parent = null,
    ): EntityIndexingRecordInterface {
    
       return $this->entityIndexingRecordFactory->create([
            'recordId' => $recordId,
            'entity' => $entity,
            'parent' => $parent, // this is used when indexing configurable variants. If the entity has no parent set this to null.
            'action' => $action,
        ]);
    }
}

```
:::

Final step is to create the pipeline YAML file to process that data before it is sent to Klevu.
`Vendor_Module::etc/pipeline/add_update.yml`. See [Pipelines](https://docs.klevu.com/klevu-magento-v4/entities-pipelines).

[title] Indexing Custom Entities
[path] Common Customisations/

<font color="#C2410C">Note: this guide covers integration of entities with a custom entity type, not the injection of additional entities into existing entity type sync (for example, sending blog posts as KLEVU_CMS alongside CMS Pages).</font>

Beyond the standard Product, Category, and CMS Page enities, the Klevu indexes support sync and return of custom entity types. Ultimately, all records are stored in the same "bucket", with the same core structure and attributes. Behaviour (such as in search) is then modified using filters and actions referencing the entity type - natively KLEVU\_PRODUCT; KLEVU\_CATEGORY; and KLEVU\_CMS.

What this means is that we can create and sync any "type" of entity with the Klevu indexes, providing it has the same basic data points and a unique entity type identifier. Frontend customisations can then handle search and display to allow integration seamlessly into your site.

## Implementing in Magento

Version 4.x of the Klevu Magento integration is designed with extensibility in mind - including the ability to inject different entity types into the indexing discovery and sync operations. This is the same extensibility used within the module itself to manage products, categories, and cms so we can follow the same steps to handle other entities.

<font color="#C2410C">Note: the creation and management of these entities is the responsibility of the integrator, though may include entities (such as blog posts) from other third party extensions.
The key requirement for integration with Klevu's indexing modules is that the entity implements either ExtensibleDataInterface or PageInterface. If integrating a third party entity which does not implement one of these interfaces, you may want need to create a custom version of the class. This is out of the scope of this guide.</font>

A [working example module can be found on Github](https://github.com/klevultd/m2-customisations/blob/main/Vendor_KlevuIndexingCustomEntities).

### Create an Entity Provider

First we need to create a service to provide those custom entities to the indexing module. This class must implement the `\Klevu\IndexingApi\Service\Provider\EntityProviderInterface` interface, and contain a `get` method which returns a `\Generator` yielding arrays of custom entities to support batching.&#x20;

The class must also contain a `getEntitySubtype` method, which often will simply contain a string of your choice. This method is primarily used to support indexing of entities which have different subtypes, such as Products (configurable, simple, variants, etc).

An [example Provider implementation can be found in the sample extension](https://github.com/klevultd/m2-customisations/blob/main/Vendor_KlevuIndexingCustomEntities/Service/Provider/CustomEntityProvider.php) on Github.

Once you have created the class, you will need to wire it in using dependency injection. You will need to create both a standard and "batched" version of the provider, though this can be achieved by simply creating a virtualType of the concrete class.

```xml
    <type name="Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider">
        <arguments>
            <argument name="logger" xsi:type="object">Klevu\Indexing\Logger\Logger</argument>
            <argument name="batchSize" xsi:type="const">Klevu\Indexing\Constants::DEFAULT_INDEXING_BATCH_SIZE</argument>
            <argument name="batchSizeValidator" xsi:type="object">Klevu\Indexing\Validator\BatchSizeValidator</argument>
        </arguments>
    </type>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider\Batched"
                 type="Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider" />
```

You will also need to create implementations of the `Klevu\Indexing\Service\Provider\EntityProviderProvider` class and inject your custom provider(s - if you are syncing multiple custom entity types via the same module). This can be done using a virtualType as follows

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityProviderProvider"
                 type="Klevu\Indexing\Service\Provider\EntityProviderProvider">
        <arguments>
            <argument name="entityProviders" xsi:type="array">
                <item name="vendor_custom_entity"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider</item>
            </argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityProviderProvider\Batched"
                 type="Klevu\Indexing\Service\Provider\EntityProviderProvider">
        <arguments>
            <argument name="entityProviders" xsi:type="array">
                <item name="vendor_custom_entity"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider\Batched</item>
            </argument>
        </arguments>
    </virtualType>
```

*Note: the item name should correspond to the entity type identifier you will use for sync (eg, for Klevu,&#x20;*`klevu_product`*,&#x20;*`klevu_category`*, and&#x20;*`klevu_cms`*)*

### Incorporate Is Indexable Conditions

As part of entity provision, we also need to tell the core module how to decide if an entity is indexable (think disabled products, or those assigned to different websites).&#x20;

The Determiner itself can be a virtualType of `Klevu\Indexing\Service\Determiner\IsIndexableDeterminer` composed of one or more IsIndexable condition classes.

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Determiner\IsIndexableDeterminer"
                 type="Klevu\Indexing\Service\Determiner\IsIndexableDeterminer">
        <arguments>
            <argument name="isIndexableConditions" xsi:type="array">
                <!-- Here you can add conditions covering entity status, published date, etc -->
                <item name="exampleIsIndexableCondition"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Determiner\ExampleIsIndexableCondition</item>
            </argument>
        </arguments>
    </virtualType>
```

An [example IsIndexableCondition](https://github.com/klevultd/m2-customisations/blob/main/Vendor_KlevuIndexingCustomEntities/Service/Determiner/ExampleIsIndexableCondition.php) can be found in the Github module.

*Note:&#x20;*`isIndexableConditions`*&#x20;are evaluated on an OR basis, meaning if any one returns true then the record is considered indexable. If you need AND conditions, that should be implemented in a single condition class at a code level.*

### Create a Discovery Provider

Next, we need to configure and inject a discovery provider so the core actions can find and index our entities. Again, this can all be done via `di.xml`

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider\Batched"
                 type="Klevu\Indexing\Service\Provider\EntityDiscoveryProvider">
        <arguments>
            <argument name="entityType" xsi:type="string">VENDOR_CUSTOM_ENTITY</argument>
            <argument name="entityProviderProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityProviderProvider\Batched</argument>
            <argument name="isIndexableDeterminer"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Determiner\IsIndexableDeterminer</argument>
            <!-- If a custom entity can be excluded at a store level, we need this to be true -->
            <argument name="isCheckIsIndexableAtStoreScope" xsi:type="boolean">false</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider"
                 type="Klevu\Indexing\Service\Provider\EntityDiscoveryProvider">
        <arguments>
            <argument name="entityType" xsi:type="string">VENDOR_CUSTOM_ENTITY</argument>
            <argument name="entityProviderProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityProviderProvider</argument>
            <argument name="isIndexableDeterminer"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Determiner\IsIndexableDeterminer</argument>
            <!-- If a custom entity can be excluded at a store level, we need this to be true -->
            <argument name="isCheckIsIndexableAtStoreScope" xsi:type="boolean">true</argument>
        </arguments>
    </virtualType>

    <type name="Klevu\Indexing\Service\EntityDiscoveryOrchestratorService">
        <arguments>
            <argument name="discoveryProviders" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider\Batched</item>
            </argument>
        </arguments>
    </type>
```

### Inject Custom Entity Discovery into Core Filters

Other than injecting into the Entity Discovery Orchestrator Service, we also need to add our provider to the indexing filter services.

```xml
    <type name="Klevu\Indexing\Service\FilterEntitiesToDeleteService">
        <arguments>
            <argument name="discoveryProviders" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider</item>
            </argument>
        </arguments>
    </type>

    <type name="Klevu\Indexing\Service\FilterEntitiesToSetToIndexableService">
        <arguments>
            <argument name="discoveryProviders" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider</item>
            </argument>
        </arguments>
    </type>

    <type name="Klevu\Indexing\Service\FilterEntitiesToSetToNotIndexableService">
        <arguments>
            <argument name="discoveryProviders" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityDiscoveryProvider</item>
            </argument>
        </arguments>
    </type>
```

### Create an Entity Indexing Record Creator

Once we have our provider wired in, we need a service to convert those entities into Indexing Records via an implementation of the `\Klevu\IndexingApi\Service\EntityIndexingRecordCreatorServiceInterface` interface.

This class must contain an execute method which receives the record ID, an action (add, update, delete), the entity itself (which is typecast to `PageInterface|ExtensibleDataInterface` hence the custom entity mentioned at the start of the guide must implement one of these interfaces), and an option parent entity (again typecast).&#x20;

*Note: It's unlikely you will need to implement parent-child relations though, if required, you can reference the record creator in Klevu's IndexingProducts module, where this is used for configurable variants).*

An [example Creator service](https://github.com/klevultd/m2-customisations/blob/main/Vendor_KlevuIndexingCustomEntities/Service/EntityIndexingRecordCreatorService.php) can be found in the Github module.

### Add Indexing Pipeline Definitions

Next we'll take a slight detour into our pipeline definitions. There are three actions which need to be configured: Add, Update, and Delete. In most cases, however, Add and Update can use the same pipeline definitions as the payload and endpoint remain the same and PATCH support will not be introduced to this module.

By convention, pipeline YAML files live in `etc/pipeline`. For this module, we will not be nesting beneath the entity identifier (eg `etc/pipeline/vendor_custom_entity`, though if you are supporting multiple entities in a single module then this is recommended).

*Note: We also use imports (again, just a convention) to separate out distinct parts of the pipeline and reduce duplication. For this example, we are not going to the extent of using separate files for individual attributes, but a complex example can be found in the core&#x20;*[IndexingProducts](https://github.com/klevu/module-m2-indexing-products/)*&#x20;module.*

As such, we would expect to see YAML files for

- Add / Update operations
- Delete operations
- Entity Transformation (for inclusion in the Add / Update file)

[Examples of these files](https://github.com/klevultd/m2-customisations/tree/main/Vendor_KlevuIndexingCustomEntities/etc/pipeline) can be found in the sample module on Github.

A basic overview of the actions you will find in those pipelines:

- Logging at the start and end of the process
- Iteration over the provided batches
- Iteration over records within the batch
- Registration of some variables to context, to allow access deeper in the pipeline as required
- Transformation of the custom entity object int JSON representation suitable for sync
- Processing of the payload, including send to Klevu's APIs

Within the transformation stage, we use the same record structure as for any indexing API request. You can see more about this structure in the [Data Indexing documentation](https://docs.klevu.com/indexing-apis/overview#record-structure).

Once you have created these files, you will need to register them with the core Pipeline Configuration Provider via `di.xml`, which allows our core indexing process to reference them when an action is initiated for your (or all) entities.

```xml
    <type name="Klevu\PlatformPipelines\Service\Provider\PipelineConfigurationProvider">
        <arguments>
            <argument name="pipelineConfigurationFilepaths" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY::add" xsi:type="string">Vendor_KlevuIndexingCustomEntities::etc/pipeline/add_update.yml</item>
                <item name="VENDOR_CUSTOM_ENTITY::delete" xsi:type="string">Vendor_KlevuIndexingCustomEntities::etc/pipeline/delete.yml</item>
                <item name="VENDOR_CUSTOM_ENTITY::update" xsi:type="string">Vendor_KlevuIndexingCustomEntities::etc/pipeline/add_update.yml</item>
            </argument>
        </arguments>
    </type>
```

### Configure Indexing

Once you have the creator and pipeline definitions, you can configure the indexing record providers and inject them into the core indexer services. Again, this is all done using `di.xml`

*Configure Indexing Record Providers*

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider"
                 type="Klevu\Indexing\Service\Provider\Sync\EntityIndexingRecordProvider">
        <arguments>
            <argument name="entityProviderProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\EntityProviderProvider</argument>
            <argument name="indexingRecordCreatorService"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\EntityIndexingRecordCreatorService</argument>
            <argument name="entityType" xsi:type="string">VENDOR_CUSTOM_ENTITY</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Add"
                 type="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider">
        <arguments>
            <argument name="action" xsi:type="string">Add</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Update"
                 type="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider">
        <arguments>
            <argument name="action" xsi:type="string">Update</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Delete"
                 type="Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider">
        <arguments>
            <argument name="action" xsi:type="string">Delete</argument>
        </arguments>
    </virtualType>
```

*Create entity indexers*

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Add"
                 type="Klevu\Indexing\Service\EntityIndexerService">
        <arguments>
            <argument name="entityIndexingRecordProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Add</argument>
            <argument name="pipelineIdentifier" xsi:type="string">VENDOR_CUSTOM_ENTITY::add</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Delete"
                 type="Klevu\Indexing\Service\EntityIndexerService">
        <arguments>
            <argument name="entityIndexingRecordProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Delete</argument>
            <argument name="pipelineIdentifier" xsi:type="string">VENDOR_CUSTOM_ENTITY::delete</argument>
        </arguments>
    </virtualType>

    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Update"
                 type="Klevu\Indexing\Service\EntityIndexerService">
        <arguments>
            <argument name="entityIndexingRecordProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\Sync\EntityIndexingRecordProvider\Update</argument>
            <argument name="pipelineIdentifier" xsi:type="string">VENDOR_CUSTOM_ENTITY::update</argument>
        </arguments>
    </virtualType>
```

*Finally, hook up with the Entity Sync Orchestrator*

```xml
    <type name="Klevu\Indexing\Service\EntitySyncOrchestratorService">
        <arguments>
            <argument name="entityIndexerServices" xsi:type="array">
                <item name="VENDOR_CUSTOM_ENTITY" xsi:type="array">
                    <item name="delete"
                          sortOrder="10"
                          xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Delete</item>
                    <item name="update"
                          sortOrder="20"
                          xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Update</item>
                    <item name="add"
                          sortOrder="30"
                          xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\EntityIndexerService\Add</item>
                </item>
            </argument>
        </arguments>
    </type>
```

### Add Configuration to Enable/Disable Sync via Backend

Optionally, you can add the ability to disable sync for your custom entities via Stores > Configuration by configuring a Yes/No field in the backend (standard Magento customisation).

The core Klevu module contains a class to provide scoped configuration easily via `di.xml` configuration, which we recommend using.

```xml
    <virtualType name="Vendor\KlevuIndexingCustomEntities\Service\Provider\SyncEnabledProvider"
                 type="Klevu\Configuration\Service\Provider\ScopeConfigProvider">
        <arguments>
            <argument name="path" xsi:type="string">vendor/klevu_indexing_custom_entities/sync_enabled</argument>
            <argument name="returnType"
                      xsi:type="const">Klevu\Configuration\Service\Provider\ScopeConfigProvider::TYPE_BOOLEAN</argument>
        </arguments>
    </virtualType>
```

You can then use this in your custom entity provider to prevent return of any entities when sync is disabled.

```php
class CustomEntityProvider implements EntityProviderInterface
{
    // snip
    private readonly ScopeConfigProviderInterface $syncEnabledProvider;

    public function __construct(
        // snip
        ScopeConfigProviderInterface $syncEnabledProvider,
    ) {
        // snip
        $this->syncEnabledProvider = $syncEnabledProvider;
    }

    /**
     * @param StoreInterface|null $store
     * @param int[]|null $entityIds
     *
     * @return \Generator<CustomEntityInterface[]>|null
     */
    public function get(
        ?StoreInterface $store = null,
        ?array $entityIds = [],
    ): ?\Generator {
        // Included to support disabling sync via configuration
        if (!$this->syncEnabledProvider->get()) {
            return null;
        }
```

```xml
    <type name="Vendor\KlevuIndexingCustomEntities\Service\Provider\CustomEntityProvider">
        <arguments>
           <!-- snip -->
            <argument name="syncEnabledProvider"
                      xsi:type="object">Vendor\KlevuIndexingCustomEntities\Service\Provider\SyncEnabledProvider</argument>
        </arguments>
    </type>
```

## Responding to Changes

The implementation as detailed above (and in the example module) covers integrating custom entities into the core discovery and sync process. This means that that the provided `klevu_indexing_discover_entities` cron, and `klevu:indexing:entity-discovery` / `klevu:indexing:entity-update` CLI command will find your records for indexing; and that the `klevu_indexing_sync_entities` cron and `klevu:indexing:entity-sync` CLI command will send your records to Klevu.

The examples will not, however, respond to changes made during the course of day-to-day operations, for example record saves.

You will need to implement plugins or observers to listen for these changes and trigger an entity update in response.

These plugins may trigger the `\Klevu\IndexingApi\Service\EntityUpdateResponderServiceInterface::execute` via an implementation in your module.&#x20;

A straightforward example of this can be found in the [IndexingCms](https://github.com/klevu/module-m2-indexing-cms/) module either in the `\Klevu\IndexingCms\Plugin\CmsPageResourceModelPlugin` plugin or `\Klevu\IndexingCms\Observer\CmsPageDeleteObserver` observer.
The responder service implementation can be found at `\Klevu\IndexingCms\Service\EntityUpdateResponderService`

## Resources

- [Example module (Github)](https://github.com/klevultd/m2-customisations/blob/main/Vendor_KlevuIndexingCustomEntities)
- [IndexingProducts module (klevu/module-m2-indexing-products)](https://github.com/klevu/module-m2-indexing-products/)
- [IndexingCms module (klevu/module-m2-indexing-cms)](https://github.com/klevu/module-m2-indexing-cms/)


[title] Analytics
[path] /

# Overview

Required for conversion rate reporting as well as machine learning, the Magento module will send data for all orders placed on the store being synchronised, including those placed through the Magento admin panel.

Data is queued for synchronisation after the order is first created in Magento, and sent to Klevu’s APIs in a background process a short time later to ensure synchronisation actions do not interfere with the speed and stability of the installation. Orders can also be manually queued for synchronisation, for example when integrating a store with existing order history.

# Quick Reference

## CLI Commands

| **Command**                             | **Purpose**                                                                             |
| --------------------------------------- | --------------------------------------------------------------------------------------- |
| `klevu:analytics:queue-orders-for-sync` | Adds Magento orders to the internal queue to be processed in an upcoming sync operation |
| `klevu:analytics:sync-orders`           | Sends unprocessed order records to Klevu’s analytics APIs                               |

## Cron Jobs

| **Code**                                      | **Schedule**                        | **Group** |                                                                    |
| --------------------------------------------- | ----------------------------------- | --------- | ------------------------------------------------------------------ |
| `klevu_analytics_remove_synced_order_history` | Every day at midnight (`0 0 * * *`) | `klevu`   | Prunes order history records, if enabled in configuration settings |
| `klevu_analytics_requeue_stuck_orders`        | On the hour (`0 * * * *`)           | `klevu`   | Moves orders stuck in “processing” back into the queue for sync    |
| `klevu_analytics_sync_orders`                 | Custom (default `*/5 * * * *`)      | `klevu`   | Sends unsynced orders to Klevu’s analytics APIs                    |

## Config Settings

**Klevu** > **Data Sync** > **Order Analytics**

Sync status, frequency, and order status exclusions list

**Klevu** > **Developer Settings** > **Order Analytics**

Contains advanced settings primarily designed to tweak performance, data provision, and other system-related configuration

**Klevu** > **Developer Settings > Logging**

Allows setting the verbosity of analytics related messages

## Backend Interfaces

Additional sync-related data added to the native Magento **Order Grid** and **View Order** screens.

[title] Configuration Settings and Logging
[path] Analytics/

# Configuration Settings

The following settings are available under **Stores** > *Settings* > **Configuration**

| **Klevu** > **Data Sync** > **Order Analytics** | **Scope**     |                                                                                                                                                                                                                                                                                                                                     |
| ----------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order Sync Status                               | \[store view] | Controls whether to queue and/or send order information to Klevu’s servers.&#xA;Can be overridden in CLI commands with the --ignore-sync-enabled-flag argument.                                                                                                                                                                     |
| Order Sync Frequency                            | \[global]     | The schedule used by Magento’s native cron runner to execute sync operations. If disabled, you will need to implement your own scheduled sync in order to send data to Klevu.<br />Default: Every 5 minutes (`*/5 * * * *`)<br />Note: timings are based “on the hour”, eg “Every 5 minutes” would include 00:00, 00:05, 00:10, etc |
| Exclude Statuses From Sync                      | \[store view] | Allows selection of order status(es) - including custom - in which orders will not be sent to Klevu when sync actions are performed.                                                                                                                                                                                                |

| **Klevu** > **Developer Settings** > **Order Analytics**   | **Scope**     |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ---------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| IP Address Field for Order Data                            | \[store view] | Which order data field to use when extracting an order’s IP address. Choose from “Remote IP” (default; uses remote\_ip field) and “X Forwarded For” (uses x\_forwarded\_for).<br />If your installation is sending data but it is not being included in conversion rate statistics, you may need to change this field - especially if your system sits behind WAF / CDN                                                                                                                                                                      |
| Order Sync Max Batch Size                                  | \[global] \*  | \[global] \*<br />The maximum number of orders processed in a single CLI or cron execution. <br />This setting is empty by default, meaning all unsent records will be attempted each time a sync is processed. Entering a value here will cause execution to exit once the configured maximum records have been attempted (starting from the earliest). &#xA;You should leave this field empty unless you are encountering issues with memory or execution time, where a lower batch size and higher sync frequency may mitigate the issue. |
| Order Record Max Sync Attempts                             | \[store view] | The maximum number of times a record will attempt to sync before being classed as “failed” and removed from the sync queue.                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Consider Processing Orders Stuck After (minutes)           | \[global]     | When stuck record processing is executed (see *Sending Order Information to Klevu&#x20;*> *Stuck Records&#x20;*&#x73;ection above), this setting is used to determine the cut off time for records. &#xA;ie, if the cron runs at 10:00am, orders which transitioned to a sync status of “processing” at 9:45am or earlier (and are still processing) will be modified.                                                                                                                                                                       |
| Remove History for Successfully Synced Orders After (days) | \[global]     | How many days to retain sync history items for orders which have been sent to Klevu successfully. By default, all sync history will be retained.<br />                                                                                                                                                                                                                                                                                                                                                                                       |
| Remove History for Failed Synced Orders After (days)       | \[global]     | How many days to retain sync history items for orders which sync has been attempted but failed. By default, all sync history will be retained.                                                                                                                                                                                                                                                                                                                                                                                               |

| **Klevu** >**&#x20;Developer Settings&#x20;**> **Logging** | **Scope**     |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ---------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Analytics Log Level                                        | \[store view] | The verbosity of logging performed for actions taken by the Analytics module, or any of its children, including within pipelines.<br />By default, this should be left as Standard or Errors Only (for established, heavily trafficked stores) to keep log sizes to a minimum. <br />When troubleshooting, especially in non-production accounts, Verbose logging is essential; therefore, when sending debug logs to the Klevu support team, please ensure this has been updated for any / all stores encountering issues. |



&#x20; Orders will continue to be queued, meaning changes to this setting or the status of the order (eg, once payment has been taken) may cause orders to be sent at a later stage. Changing this setting or the order status (eg, marking as fraud) will not affect orders already sent to Klevu.

&#x20;This setting will not differentiate based on order state, for example where Suspected Fraud is assigned to both Payment Review and Processing states

&#x20;As orders batches comprise records from all enabled stores, implementing a batch limit may cause some operations to exclude lower trafficked stores entirely.

&#x20;This value includes the initial sync, as every order must be attempted at least once. A value of zero or lower, therefore, will be treated internally as “1”

&#x20;This threshold applies to the individual history items, so orders whose processing has spanned multiple days may see partial history.

&#x20;The order’s current sync status is considered during processing, meaning that even if the record failed to sync prior to a success send, this threshold will apply to **all** its associated history items.

&#x20;This threshold applies to the individual history items, so orders whose processing has spanned multiple days may see partial history.

&#x20;The order’s current sync status is considered during processing, meaning that even if the record send successfully but was re-queued and failed this threshold will apply to **all** its associated history items.

:::hint{type="info"}
After changing any configuration settings, please remember to clear the Config cache.
:::

# Logging

The Analytics group of modules implement dedicated logs to segregate them from other areas, grouped by store name. These logs can be found at `/var/log/klevu/[store_code]/klevu-[store_code]-analytics.log` .

To control the level of detail included in analytics logs (configurable on a store-by-store basis), please use the **Klevu** > **Developer Settings** > **Logging** > **Analytics Log Level** setting.

[title] CMS Page with the same ID already exists error
[path] Troubleshooting/

# Problem

After installation of Klevu and API key integration, some stores may experience the following error when running sync operations, or saving CMS pages:

:::hint{type="danger"}
Item (Magento\Cms\Model\Page) with the same ID "\{id}" already exists
:::

# Cause

The root cause of this is an unexpected CMS Page -> Store View configuration and how that conflicts with the way Klevu collects pages to process.

Klevu will attempt to retrieve all records which belong to *either* All Store Views or the specific store being synchronised. Where a CMS page has been redundantly assigned to both All Store Views and the store view being synced, duplicate records may be picked up by Klevu.

An example of this configuration is below

![](https://archbee-image-uploads.s3.amazonaws.com/txIf3IazdJsdQky_oYUyV-JPO90vXLQttmvDeR-ZLaJ-20250911-142022.png)

# Solution

Update your store's configuration to assign problematic CMS pages (the database ID is provided in the error message) to be assigned to *either* All Store Views or specific stores.

If you have database access, you can check the `cms_page_store` table to find duplicate `page_id` rows where at least one row has a `store_id` of `0`

## Workaround

If are unable to resolve the configuration, you can create a small patch for the `klevu/module-v4-indexing-cms` module.

In the `Klevu\IndexingCms\Service\Provider\CmsEntityProvider::getPageCollection` , look for the modifications made to the `$pageCollection` database select when a `$store` value is passed.
At the end of this block, add the following line

```php
$select->group('main_table.page_id');
```

Ref: [CmsEntityProvider @ 3.1.1 on Github](https://github.com/klevu/module-m2-indexing-cms/blob/3.1.1/Service/Provider/CmsEntityProvider.php#L174)

The block should look like this after (code correct at module v3.1.1)

```php
// snip
        if ($store) {
            $connection = $pageCollection->getConnection();
            $select = $pageCollection->getSelect();
            $select->joinInner(
                name: ['store' => $pageCollection->getTable('cms_page_store')],
                cond: implode(
                    ' ' . Select::SQL_AND . ' ',
                    [
                        sprintf(
                            'main_table.page_id = store.%s',
                            $connection->quoteIdentifier($linkField),
                        ),
                        $connection->quoteInto('store.store_id IN (0,?)', (int)$store->getId()),
                    ],
                ),
                cols: ['store.store_id'],
            );
            $select->group('main_table.page_id');
        }
// snip
```






[title] Search
[path] Frontend/


[title] Sync
[path] Indexing/Attributes/

:::hint{type="info"}
Attribute sync is responsible for sending attribute data to Klevu.&#x20;
:::

:::hint{type="warning"}
The type of API request depends on the `next_action` column in the `klevu_indexing_attribute` database table. If that column is set to `Add` then an add request will be sent, if it is empty no request will be sent.&#x20;

The population of `klevu_indexing_attribute` database table is controlled by attribute discovery and update. Attribute sync does not determine the action to be performed.
:::

Attribute sync is triggered:

- via cron
- via CLI

`\Klevu\Indexing\Service\AttributeSyncOrchestratorService` responsible for attribute sync. All the above methods of triggering attribute sync use this service.

### Cron

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, attribute sync cron tasks use the dedicated `klevu` cron group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

Attributes sync runs every 10 minutes by default. This can be configured in the Magento admin, `Stores > Configuration > Klevu > Data Sync > Indexing >  Attribute Indexing Sync Frequency`.
The default setting can be found here `module-m2-indexing/etc/config.xml`
The configuration for the cron can be found here `module-m2-indexing/etc/crontab.xml`

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_attributes"
     instance="Klevu\Indexing\Cron\SyncAttributes"
     method="execute">
    <config_path>klevu/indexing/attribute_cron_expr</config_path>
</job>
```
:::

### CLI

`klevu:indexing:attribute-sync`

The sync can also be triggered via CLI and has 2 optional parameters&#x20;

- `api-keys` - \[optional] comma-separated list of API keys to sync
- `attribute-types` - \[optional] comma-separated list of attribute types to sync, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

Increasing the verbosity of the command will give you more information using `-v`, `-vv`, or `-vvv`

e.g

```shell
bin/magento klevu:indexing:attribute-sync \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" \
    -vvv
```

:::hint{type="warning"}
If an attribute has been registered with Klevu for indexing that does not mean it is automatically sent to Klevu. It means it can be sent to Klevu.&#x20;

Entity data indexed to Klevu is defined in the [indexing pipelines](https://docs.klevu.com/klevu-magento-v4/entities-pipelines) YAML files.&#x20;
For custom attributes, you can either&#x20;

- enable autogeneration of the YAML files in the admin at `Stores > Configuration > Klevu > Developer Settings > Pipelines > Enable autogeneration of configuration overrides` and select the product types to send this data for in `Automatically Generate Pipeline Configuration For` section of the attribute properties.
- add your own YAML file for the attribute - see [pipelines customisation](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation)
:::


[title] Attribute Mapping
[path] Indexing/Attributes/

It is possible to map Magento attributes to Klevu attributes via `di.xml`
The modules already map some attributes where the names in Klevu and Magento differ. e.g. Magento's `short_description` to Klevu's `shortDescription`.

The current product attribute mapping can be found in `module-m2-indexing-products/etc/di.xml` and looks like this:

:::CodeblockTabs
module-m2-indexing-products/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Mapper\MagentoToKlevuAttributeMapper"
             type="Klevu\Indexing\Service\Mapper\MagentoToKlevuAttributeMapper">
  <arguments>
    ...
    <argument name="attributeMapping" xsi:type="array">
      <item name="image" xsi:type="null"/>
      <item name="klevu_image" xsi:type="string">image</item>
      <item name="klevu_rating" xsi:type="string">rating</item>
      <item name="klevu_rating_count" xsi:type="string">ratingCount</item>
      <item name="quantity_and_stock_status" xsi:type="string">inStock</item>
      <item name="short_description" xsi:type="string">shortDescription</item>
      <item name="url_key" xsi:type="string">url</item>
    </argument>
  </arguments>
</virtualType>
```
:::

### Adding Mapping for Attributes

If instead of using the Magento attribute `description` for the Klevu attribute `description` you wanted to use `my_custom_attribute`. Create your own module and add `etc/di.xml` like this

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="attributeMapping" xsi:type="array">
            <item name="my_custom_attribute" xsi:type="string">description</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Now if you access `my_custom_attribute` in Magento admin you’ll see that the Klevu section can no longer be updated as it is mapped to a standard Klevu attribute and standard Klevu attributes are immutable. However, the `description` attribute will be editable as it is no longer mapped to a standard Klevu attribute.

If `description` is also set to be registered with Klevu this will cause an issue as there are 2 Magento attributes mapped to the same Klevu attribute (if no mapping is in place then an attribute will use its attribute code). Therefore mapping for `description` would also be required.
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="attributeMapping" xsi:type="array">
            <item name="my_custom_attribute" xsi:type="string">description</item>
            <item name="description" xsi:type="string">someOtherField</item>
        </argument>
    </arguments>
</virtualType>
```
:::

or

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="attributeMapping" xsi:type="array">
            <item name="my_custom_attribute" xsi:type="string">description</item>
            <item name="description" xsi:type="null"/>
        </argument>
    </arguments>
</virtualType>
```
:::


[title] Theme JS
[path] Frontend/


[title] Discovery
[path] Indexing/Attributes/

## Attribute Discovery

:::hint{type="warning"}
Attribute discovery does not send any data to Klevu.

Its only purpose is to add missing attributes to the `klevu_indexing_attribute` database table or to set attributes that are no longer indexable to have a `next action` of `Delete`.
:::

Note: all Magento category and product attributes are added here, even if they do not currently need to be registered with Klevu.

Attribute discovery will:

- add any missing attributes and determine if those [attributes are indexable](https://docs.klevu.com/klevu-magento-v4/attribute-is-indexable-determiner).&#x20;
- set any attributes which are no longer indexable, but were previously registered, to have a `next_action` of `Delete`.&#x20;
- set any attributes that have become indexable to have a `next_action` of `Add`.&#x20;

Attribute discovery will **NOT**:

- determine if an attribute requires an update.
- send any data to Klevu.

Attribute discovery is triggered:

- on account integration
- via plugins
- via observers
- via cron
- via CLI

`\Klevu\Indexing\Service\AttributeDiscoveryOrchestratorService`is responsible for attribute discovery. All the above methods of triggering attribute discovery use this service.

### Cron

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, attribute discovery cron tasks use the dedicated `klevu` cron group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

Attribute discovery runs once a day via cron.
The configuration for the cron can be found here `module-m2-indexing/etc/crontab.xml`

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_discover_attributes"
     instance="Klevu\Indexing\Cron\DiscoverAttributes"
     method="execute">
    <schedule>52 1 * * *</schedule>
</job>
```
:::

### CLI

`klevu:indexing:attribute-discovery`

The discovery can also be triggered via CLI and has 2 optional parameters&#x20;

- `api-keys` - \[optional] comma-separated list of API keys to run discovery for
- `attribute-types` - \[optional] comma-separated list of  attribute types to run discovery for, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

e.g

```shell
bin/magento klevu:indexing:attribute-discovery \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key"
    
```


[title] Frontend Overview
[path] Frontend/

The Frontend module `module-m2-frontend` creates a base for other frontend modules to inject data into.&#x20;
The frontend module itself has no knowledge of Category Navigation, Recommendations, Search or Metadata. They are added via their own modules `module-m2-frontend-categorynavigation`, `module-m2-frontend-recommendations`, `module-m2-frontend-search` and `module-m2-frontend-metadata`.&#x20;

More modules may be added in the future to support new frontend solutions.

### Removal of Modules

If you are not signed up for all Klevu frontend solutions you may remove the modules for the solutions not in use by updating your `composer.json`

**Remove Category Navigation**

```json
"replace": {
    "klevu/module-m2-frontend-metadata-categorynavigation": "*",
    "klevu/module-m2-frontend-categorynavigation": "*"
},
```

**Remove Recommendations**

```json
"replace": {
    "klevu/module-m2-frontend-metadata-recommendations": "*",
    "klevu/module-m2-frontend-recommendations": "*",
},
```

**Remove Search**

```json
"replace": {
    "klevu/module-m2-frontend-metadata-search": "*",
    "klevu/module-m2-frontend-search": "*"
},
```

If you are using [Klevu Headless SDK](https://docs.klevu.com/headless-sdk) to build the frontend of your store then you can remove all Klevu frontend modules.

```shell
composer remove "klevu/module-m2-frontend"
```

## Logging

The frontend group of modules implement dedicated logs to segregate them from other areas, grouped by store name. These logs are found at `/var/log/klevu/[store_code]/klevu-[store_code]-frontend.log`.

To control the level of detail included in frontend logs (configurable on a store-by-store basis), please use the **Klevu** > **Developer Settings** > **Logging** > **Frontend Log Level** setting. See [Logging](https://docs.klevu.com/klevu-magento-v4/logging) for more information.

[title] Untitled
[path] /


[title] Theme JS Overview
[path] Frontend/Theme JS/

## Template JS Documentation

Klevu Template JS documentation can be found here [https://docs.klevu.com/template-js](https://docs.klevu.com/template-js).

## Best Practice

### Including Javascript

We have added 2 containers to the layout, one in head and one before body end. We recommend adding all Klevu related Javascript to these 2 contains.&#x20;
These 2 contains are named `Klevu_Frontend.head.additional` and `Klevu_Frontend.before.body.end`.

This makes it very easy to remove all Klevu scripts from a particular page. We already remove all Klevu Javascript from the checkout page, like so.

:::CodeblockTabs
module-m2-frontend/view/frontend/layout/checkout\_index\_index.xml

```xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="Klevu_Frontend.head.additional" remove="true" />
        <referenceContainer name="Klevu_Frontend.before.body.end" remove="true" />
    </body>
</page>
```
:::

### Ensure Klevu is ready before accessing it

Calling any `klevu` methods before the Klevu JS has loaded will result in errors on the frontend. This may occur if there is a delay in loading the core Klevu library for any reason (e.g code being added being added higher up the page or async being added to the script tag).

It is always a good idea to wrap JS containing calls to `klevu` in `window._klvReady.push(function(){})`. This ensures the code wrapped inside `_klvReady` is not fired until `klevu` is available.
e.g.

```php
<?php

$scriptString = <<<script

window._klvReady = window._klvReady || [];
window._klvReady.push(function() {  
  /** 
   * add your code here 
   * e.g. 
   * klevu.setObjectPath(
   *   klevuSettings,
   *   'search.showQuickOnEnter',
   *   klevu.toBoolean(true)
   * );
   */
});

script;
?>

<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript'],
    content: $scriptString,
    textContent: false
) ?>

```

:::hint{type="warning"}
Note: `window._klvReady.push` is omitted from the code examples in the rest this documentation for brevity.
:::


[title] Category Navigation
[path] Frontend/Is Enabled Determiner/

When Category Navigation `Ordering & Rendering` is set the Klevu Theme is enabled for all Categories.&#x20;

This behaviour can be amended by injecting custom `isEnabledConditions` into the `isEnabledDeterminer`.

The default behaviour of the determiner for category navigation checks:

- If the store is integrated with Klevu
- If category navigation is enabled
- If the route is a category
- If the category is displaying products

:::CodeblockTabs
module-m2-frontend-categorynavigation/etc/di.xml

```xml
<type name="Klevu\FrontendCategoryNavigation\Service\Action\UpdateCategoryPageLayoutAction">
    <arguments>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_integrated"
                  xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
            <item name="klevu_catnav_enabled"
                  xsi:type="object">Klevu\FrontendCategoryNavigation\Service\IsEnabledCondition\IsCatNavEnabledCondition</item>
            <item name="klevu_category_route"
                  xsi:type="object">Klevu\FrontendCategoryNavigation\Service\IsEnabledCondition\IsCategoryRouteCondition</item>
            <item name="klevu_category_display_products"
                  xsi:type="object">Klevu\FrontendCategoryNavigation\Service\IsEnabledCondition\IsCategoryDisplayingProductsCondition</item>
        </argument>
    </arguments>
</type>
```
:::

If all these return true, the category navigation layout handle will be added to the page.

### Enable for a subset of categories

Say we only wanted to enable Klevu's Category Navigation if the category ID was odd.

Inject your own `isEnableCondition`

:::CodeblockTabs
module-m2-frontend-categorynavigation/etc/di.xml

```xml
<type name="Klevu\FrontendCategoryNavigation\Service\Action\UpdateCategoryPageLayoutAction">
    <arguments>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="is_odd_category"
                  xsi:type="object">Vendor\Model\Service\IsEnabledCondition\IsCategoryOddCondition</item>
        </argument>
    </arguments>
</type>
```
:::

Create the Condition

:::CodeblockTabs
Vendor/Model/Service/IsEnabledCondition/IsCategoryOddCondition.php

```php
<?php

declare(strict_types=1);

namespace Vendor\Module\Service\IsEnabledCondition;

use Klevu\FrontendCategoryNavigation\Service\IsEnabledCondition;
use Klevu\Registry\Api\CategoryRegistryInterface;

class IsCategoryOddCondition implements IsEnabledConditionInterface
{
    public function __construct(CategoryRegistryInterface $categoryRegistry)
    {
        $this->categoryRegistry = $categoryRegistry;
    }
    
    public function execute(): bool
    {
        $category = $this->categoryRegistry->getCurrentCategory();
        
        return $category->getId() & 1;
    }
}

```
:::

See `module-m2-frontend-categorynavigation/Service/IsEnabledCondition` for more examples of `isEnabledDeterminer` classes.

[title] Analytics Overview
[path] Analytics/

Required for conversion rate reporting as well as machine learning, the Magento module will send data for all orders placed on the store being synchronised, including those placed through the Magento admin panel.

Data is queued for synchronisation after the order is first created in Magento, and sent to Klevu’s APIs in a background process a short time later to ensure synchronisation actions do not interfere with the speed and stability of the installation. Orders can also be manually queued for synchronisation, for example when integrating a store with existing order history.

## Quick Reference

### CLI Commands

| **Command**                             | **Purpose**                                                                             |
| --------------------------------------- | --------------------------------------------------------------------------------------- |
| `klevu:analytics:queue-orders-for-sync` | Adds Magento orders to the internal queue to be processed in an upcoming sync operation |
| `klevu:analytics:sync-orders`           | Sends unprocessed order records to Klevu’s analytics APIs                               |

### Cron Jobs

| **Code**                                      | **Schedule**                        | **Group** |                                                                    |
| --------------------------------------------- | ----------------------------------- | --------- | ------------------------------------------------------------------ |
| `klevu_analytics_remove_synced_order_history` | Every day at midnight (`0 0 * * *`) | `klevu`   | Prunes order history records, if enabled in configuration settings |
| `klevu_analytics_requeue_stuck_orders`        | On the hour (`0 * * * *`)           | `klevu`   | Moves orders stuck in “processing” back into the queue for sync    |
| `klevu_analytics_sync_orders`                 | Custom (default `*/5 * * * *`)      | `klevu`   | Sends unsynced orders to Klevu’s analytics APIs                    |

### Config Settings

**Klevu** > **Data Sync** > **Order Analytics**

Sync status, frequency, and order status exclusions list

**Klevu** > **Developer Settings** > **Order Analytics**

Contains advanced settings primarily designed to tweak performance, data provision, and other system-related configuration

**Klevu** > **Developer Settings > Logging**

Allows setting the verbosity of analytics related messages

### Backend Interfaces

Additional sync-related data added to the native Magento **Order Grid** and **View Order** screens.

[title] Custom Attribute Name Prefix
[path] Indexing/Entities/Categories/

As Magento has separate attributes for products and categories and these attributes can have the same name. Klevu does not differentiate attributes between entity types and therefore a name clash could occur with category and product attributes overwriting each other. To mitigate this we have added a prefix to any custom category attributes. By default this prefix is set to `cat__`.

:::CodeblockTabs
module-m2-indexing-categories/etc/di.xml

```xml
<virtualType name="Klevu\IndexingCategories\Service\Mapper\MagentoToKlevuAttributeMapper"
             type="Klevu\Indexing\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="entityType"
                  xsi:type="const">Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE</argument>
        
        <!-- CATEGORY ATTRIBUTE PREFIX -->
        <argument name="prefix" xsi:type="string">cat__</argument>
        
        <argument name="attributeMapping" xsi:type="array">
            <item name="path" xsi:type="string">categoryPath</item>
            <item name="url_key" xsi:type="string">url</item>
        </argument>
    </arguments>
</virtualType>
```
:::

:::hint{type="info"}
The prefix only applies to custom attributes. Klevu standard attributes are not prefixed.
:::

You are free to change this prefix like so

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingCategories\Service\Mapper\MagentoToKlevuAttributeMapper">
    <arguments>
        <argument name="prefix" xsi:type="string">prefix_</argument>
    </arguments>
</virtualType>
```
:::

:::hint{type="info"}
Note: The prefix is limited to underscores and alphanumeric characters only.
:::

:::hint{type="warning"}
If you change the prefix you’ll also need to ensure that any `cat__attribute_code` references in your pipeline YMAL files and/or frontend search requests are updated with the new prefix.
:::


[title] Configurable Product Images
[path] Indexing/Entities/Products/Untitled/

Klevu, by default, will sync the variant product image for each variant. It will also sync the configurable product image as a fallback.

The pipeline for variant images looks like this

:::CodeblockTabs
Klevu\_IndexingProducts::etc/pipeline/product/attributes/image/variant.yml

```yaml
  findImageToUse:
    pipeline: Pipeline\Fallback
    stages:
      klevuImage:
        import: Klevu_IndexingProducts::etc/pipeline/product/attributes/images/klevu_image.yml
      image:
        import: Klevu_IndexingProducts::etc/pipeline/product/attributes/images/base_image.yml
      klevuImageParent:
        import: Klevu_IndexingProducts::etc/pipeline/product/attributes/images/parent_product/klevu_image.yml
      imageParent:
        import: Klevu_IndexingProducts::etc/pipeline/product/attributes/images/parent_product/base_image.yml
      placeholder:
        import: Klevu_IndexingProducts::etc/pipeline/product/attributes/images/placeholder_image.yml
      default:
        stages:
          getImage:
            pipeline: Stage\StaticValue
            args:
              value: null
```
:::

This `Fallback` pipeline will return an image patch as soon as it finds one it can use.

- Get the Variant `Klevu Image`
- Get the Variant `Base Image`
- Get the Configurable `Klevu Image`
- Get the Configurable `Base Image`
- Get the Placeholder image. Placeholder is set before the pipeline begins and also uses a fallback
  - Get the `Klevu Image Placeholder`&#x20;
  - Get the `Base Image Placeholder`
- Finally if none of the above are set, return null.

### Remove Variant Images

If you wish to always sync the configurable product image only then we can update the pipeline to remove the variant product images.

Create a pipeline override file

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update.yml

```yaml
stages:
  iterateIndexingRecords:
    stages:
      processProduct:
        stages:
          variantProduct: # target variant products only
            stages:
              generateRecord:
                stages:
                  attributes:
                    stages: 
                      image:
                        stages:
                          findImageToUse:
                            removeStages:
                              - klevuImage
                              - image
                      
```
:::

Then add the pipeline override YAML file to the pipelines for `Add` and `Update`

:::CodeblockTabs
Vendor/module/etc/di.xml

```xml
<!-- Inject an override into the override filepath provider for Add -->
<!-- We inject the same file into Add and Update as we sync the same data, however they use different providers-->
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
            <item name="remove_variant_image_override_add"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update.yml</item>
        </argument>
    </arguments>
</virtualType>

<!-- Inject an override into the override filepath provider for Update -->
<!-- We inject the same file into Add and Update as we sync the same data, however they use different providers-->  
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
            <item name="remove_variant_image_override_update"
                      xsi:type="string">Vendor_Module::etc/pipeline/add_update.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

See [Pipeline Customisation](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation) for more information on how to customise pipelines.

[title] Discovery
[path] Indexing/Entities/

## Entity Discovery

:::hint{type="warning"}
Entity discovery does not send any data via the API to Klevu.&#x20;

Its only purpose is to add missing entities to the `klevu_indexing_entity` database table or to set entities that are no longer indexable to have a `next action` of `Delete`.
:::

Note: all Magento category, CMS page and product entities are added here, even if they do not currently need to be indexed with Klevu.

Entity discovery will:

- add any missing entities and determine if those entities are indexable.
- set any entities which are no longer indexable, but were previously registered, to have a `next_action` of `Delete`.
- set any entities that have become indexable to have a `next_action` of `Add`.

Entity discovery will **NOT**:

- determine if an entity requires an update.
- send any data to Klevu.

Entity discovery is triggered:

- on account integration
- via plugins
- via observers
- via cron
- via CLI

`\Klevu\Indexing\Service\EntityDiscoveryOrchestratorService`is responsible for entity discovery. All the above methods of triggering entity discovery use this service.

### Cron

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, entity discovery cron tasks use the dedicated `klevu` group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

Entity discovery runs once a day via cron.
The configuration for the cron can be found here `module-m2-indexing/etc/crontab.xml`

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_discover_entities"
     instance="Klevu\Indexing\Cron\DiscoverEntities"
     method="execute">
    <schedule>0 2 * * *</schedule>
</job>
```
:::

### CLI

`klevu:indexing:entity-discovery`

The discovery can also be triggered via CLI and has 2 optional parameters

- `api-keys` - \[optional] comma-separated list of API keys to run discovery for
- `entity-types` - \[optional] comma-separated list of entity types to run discovery for,
  options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`
  - `KLEVU_CMS`

e.g

```shell
bin/magento klevu:indexing:entity-discovery \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key"

```

:::hint{type="info"}
The module does not depend on the `updated_at` for a discovery operation.
:::


[title] CMS Pages
[path] Indexing/Entities/


[title] Adding Code After Klevu()
[path] Frontend/Theme JS/

There are 2 ways to achieve this:

- [Set the value via your theme](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR). Use this if the value;
  - is different depending on the theme (you use multiple themes in your store).
  - you only have one theme.
- [Set the value via a custom module](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR). Use this if the value;
  - depends on values stored in your database.
  - depends on more complex business logic.
  - is the same across all your themes and you have a lot of themes that would require an update.

### How Code is added after `Klevu(klevuSettings)`

`Klevu(klevuSettings)` is added to your page head via layout xml here `module-m2-frontend/view/frontend/layout/default_head_blocks.xml`.
Specifically in block `Klevu_Frontend.js_settings` which adds 2 empty contain blocks, so you can inject your own code before and after `klevu(klevuSettings)`.

The template that generates the settings is `module-m2-frontend/view/frontend/templates/html/head/js_settings.phtml`.

:::CodeblockTabs
module-m2-frontend/view/frontend/templates/html/head/js\_settings.phtml

```php
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript', 'id' => 'klevu_init'],
    content: "\nif(typeof klevuSettings !== 'undefined'){klevu(klevuSettings);}\n",
    textContent: false,
) ?>

<?php
/**
 * Inject javascript into klevu_frontend.init_after 
 * to make changes after klevu() is called
 */
?>
<?= $block->getChildHtml('klevu_frontend.init_after') ?>
```
:::

***

## Adding Code Via Theme

[Magento theme structure documentation](https://developer.adobe.com/commerce/frontend-core/guide/themes/structure/).

1. In your theme create a module Klevu\_Frontend, `app/code/design/frontend/Vendor/theme/Klevu_Frontend`
2. Create a layout file to add your blocks to our contain `klevu_frontend.init_after`
   `app/code/design/frontend/Vendor/theme/Klevu_Frontend/layout/default_head_blocks.xml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/layout/default\_head\_blocks.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="klevu_frontend.init_after">
            <block name="Vendor_Theme.klevu.init_after"
                   template="Klevu_Frontend::klevu/init_after.phtml"
                   before="-"/>
        </referenceBlock>
    </body>
</page>

```
:::

3\. Create the template file that will contain your customisations `app/code/design/frontend/Vendor/theme/Klevu_Frontend/templates/klevu/init_after.phtml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/templates/klevu/init\_after.phtml

```php
<?php
$scriptString = "
  // add any customisation here
";
?>

<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript'],
    content: $scriptString,
    textContent: false
) ?>
```
:::

***

## Adding Code Via A Custom Module

Note: in the example below we have used Module `Vendor_Module`.
[Magento module creation documentation](https://experienceleague.adobe.com/en/docs/commerce-learn/tutorials/backend-development/create-module).

1. Create a custom module `Vendor_Module`, `app/code/Vendor/Module` with the following directory structure. Note full module creation is not shown here.

```none
app
- code
- Vendor
 - Module
  - view
    - layout
    - templates
```

2\. Create a layout file to add your blocks to our contain `klevu_frontend.init_after`

:::CodeblockTabs
Vendor/Module/view/frontend/layout/default\_head\_blocks.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="klevu_frontend.init_after">
            <block name="Vendor_Module.klevu.init_after"
                   template="Vendor_Module::klevu/init_after.phtml"
                   before="-"/>
        </referenceBlock>
    </body>
</page>
```
:::

3\. Create the template file that will contain your customisations&#x20;

:::CodeblockTabs
Vendor/Module/view/frontend/templates/klevu/init\_after.phtml

```php
<?php

$scriptString = "
    // add any customisation here
";
?>
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript'],
    content: $scriptString,
    textContent: false
) ?>
```
:::


[title] Images
[path] Indexing/Entities/Products/

When indexing product images we can set a different image to be indexed to Klevu from the `Base` image. `Klevu Image` is added to products as a new image type alongside the default `Base`, `Small` and `Thumbnail`. This takes advantage of the Magento image processing while allowing merchants to select which image to send to Klevu.

If `Klevu Image` is not set then the `Base` image will be sent. If the `Base` image is not set then the `Placeholder` image will be sent.&#x20;

### Setting Klevu Image and Hover Image

Select this as you would select which image to use as the thumbnail for the product.

1\. Visit the product images and videos section and select the image and hover image to send to Klevu

![](https://archbee-image-uploads.s3.amazonaws.com/Y9Igf1t4Mq0XfqFm13RFY--m8faz5Q3GYq09IpbB0IO-20250227-103807.png "Magento Product Images")

2\. Select the `Role` for the image to include `Klevu Image` or `Klevu Hover Image`

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/Y9Igf1t4Mq0XfqFm13RFY-4WLcfL5iDMjKwLXWygt4f-20250227-103918.png" size="64" width="1170" height="749" position="center" caption="Select Image Role"}

### Image Size

The image size sent to Klevu can be configured in `Stores > Configuration > Klevu > Data Sync`.
Under the `Indexing` there are 2 settings

- Product Image Width
- Product Image Height

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/lgf7Cl5LXBrsBTWIpSyW4_screenshot-2024-09-12-at-145558.png)





### Image Cache Folder and Image Regeneration

The cached image path is resolved by PathProviderInterface::get(), passing the built image params and file path.&#x20;
This follows Magento's standard convention: `pub/media/catalog/product/cache/{hash}/{image_path}`

The `{hash}` is derived from the imageParams array (width, height, type, quality, etc.) built by ParamsBuilder.&#x20;

The image is generated on demand and then served from cache on subsequent requests.&#x20;
It is only regenerated in the following cases:

If a cache doesn't exist yet,  first time the image path + params combination is encountered during indexing.

If a manual flush was done from Magento admin
If CLI command run `bin/magento catalog:images:resize`
If cache directory cleared, deleting `pub/media/catalog/product/cache/` directly


[title] FAQs and Troubleshooting
[path] Analytics/

### The Order IP address is empty or incorrect in the data sent to Klevu

Check the source data in your Magento installation (either via the view order screen, or directly in the `sales_order` database table), and ensure that the **Klevu** > **Developer Settings** > **Order Analytics&#x20;**>**&#x20;IP Address Field for Order Data&#x20;**&#x69;s set to the field containing the correct data.

If neither Remote IP or X-Forwarded-For have the correct information, you may need to speak to your systems administrator about persisting and retrieving this data.
Where the data is saved to a different field, or the wrong value from a default field is extracted, the `processOrders.iterateOrders.processOrder.execute.extractEventData.createUserProfile.createRecord.ip_address` pipeline stage should be modified to use a different extraction accessor, or the Configuration Context object updated to provide a different ---method name for the `ip_address_accessor`

***

### I have integrated an established store with Klevu - why are none of my existing orders scheduled for sync?

Existing orders are not queued for sync during integration automatically. To sync historic data, please refer to the `klevu:analytics:queue-orders-for-sync` CLI command.

***

### There are orders in klevu\_sync\_order which are never picked up (even if explicitly listed in CLI  args)

There are a number of possible causes

1. The order is in an excluded status (see **Klevu** > **Data Sync** > **Order Analytics** > **Exclude Statuses From Sync&#x20;**- defined at store scope). Orders may be queued in any status, or move into that status before a sync has executed

- The order belongs to a disabled store, either through being forced into the queue or because the store was disabled in Magento before a sync executed
- The order belongs to a store with sync disabled, either through being forced into the queue or because sync was disabled for the store before a sync executed
- You are executing a CLI command with a combination of arguments (store id, sync status, and/or order id) which does not include all orders.&#x20;
  This may be manually invoked, or as a replacement to the native cron job
- Another module has been developed or installed which affects the sort order or filters used when retrieving Order collections


[title] Klevu Module v4.x Overview
[path] /

Rebuilt from the ground up, around Klevu's new JSON indexing APIs, with a focus on Magento best practices and ease of customisation.

## Compatibility

Klevu's Magento v4 plugin will support the officially supported version of PHP and Magento. i.e. when PHP 8.1 reaches end-of-life Klevu will also drop support for PHP 8.1 in future releases. Previous releases will always be available via Github and Packagist.

- **Adobe Commerce**: `2.4.4` - `2.4.8-p1`.
- **Magento Open Source**: `2.4.4` - `2.4.8-p1`.
- **PHP**: `8.1` - `8.4`.
- **Hyvä Themes.**

:::hint{type="warning"}
For older versions of Magento, please refer to the Klevu module integration guide for versions 2.x/3.x available [here](https://help.klevu.com/support/solutions/articles/5000871252-integration-steps-for-magento-2).&#x20;
:::

### **Not Supported**

- **Adobe Commerce B2B**
  Klevu supports customer group pricing via tier prices and catalog price rules.
  Customer group visibility is planned for a future release.
  Shared catalogs are not supported.

***

## Recommended Customisation Methods

Customisation should be implemented through one of the following methods

- plugins
- events and observers
- injecting classes via `di.xml`&#x20;

**Avoid extending Klevu classes via preferences**.

:::hint{type="warning"}
If you find yourself extending a Klevu class to customise our modules please reach out to support. Either there is a better way to achieve your aims or we have not architected that area as we should have done.
:::

***

## v2.x/v3.x Features Planned for Future Release

These features are planned for a future release.

### Frontend Preserve Layout

This is not currently supported in v4.x.


[title] Known Issues
[path] Klevu Module v4.x Overview/

The version relates to the version the issue was first identified in. The issue may also exist in earlier versions.

## Version 4.1.3

### General

- App emulation for frontend does not load frontend classes. Breaks rendering in PageBuilder. Also caused issues with Breeze recompiling layout. *- fixed in&#x20;*`4.2.0`

### Frontend

- Klevu search controller does not fallback to Magento search controller when SRLP is disabled. *- fixed in&#x20;*`4.2.0`

### Indexing

- Performance issues on large catalogs 200k+ product&#x73;*&#x20;- fixed in&#x20;*`4.2.0`
- Catalog Price Rules are not taken into account when indexing via cron (Indexing via CLI works as expected) *- fixed in&#x20;*`4.2.0`
- Joining stock status to variant collection also aded an in stock filter, causing products to be unexpectedly deleted/excluded from sync *- fixed in&#x20;*`4.2.0`
- Empty values sent in product data resulting in empty values in facets and breaking variant inheritance from parent products *- fixed in&#x20;*`4.2.0`
- Converting from a simple to configurable product caused configurable to be deleted in Klevu due to incorrect order of sync actions *- fixed in&#x20;*`4.2.0`
- Klevu hover image missing from admin and not sent in data *- fixed in&#x20;*`4.2.0`

## Version 4.1.0

### Indexing

- Observers on attribute save can cause the attribute not to save if the triggering of entity updates exceeds memory limits. - *fixed in&#x20;*`4.1.1`*&#x20;release*
- Entity sync on very large stores can fail due to memory limits, causing no entries to be sent. *- partial fix in&#x20;*`4.1.1`*&#x20;release, all entities up to the point of failure are now sent. The next sync will pick up where the previous one failed. - fixed&#x20;*`4.2.0`

## Version 4.0.0

### Frontend

- Currency formatter does not respect the number of decimal places of a currency set in Magento. - *fixed in&#x20;*`4.0.1`*&#x20;release*

### Indexing

- Updates of Grouped products' associated products do not trigger an update of the grouped product.
- Updates of Bundle products' associated products do not trigger an update of the bundle product.
- Product import updates are triggered too early, potentially syncing data to Klevu before the import has completed processing.
- Configurable product creation does not always add all associated products to the `klevu_indexing_entities` table.
- Attributes registered with Klevu always send the default label and not the store label. *- fixed in&#x20;*`4.1.2`
- Updating of Configurable child/variant products stock via Configurable product page `Edit Configurations` only triggers an update of the Configurable product and not the child/variant products *- fixed in&#x20;*`4.2.0`
- Missing Observer/Plugin on some stock status changes


[title] Exclude Categories from Search Results
[path] Indexing/Entities/Categories/

By default, all categories indexed to Klevu have a visibility of `search`.&#x20;
There are 2 possible approaches to change this depending on your needs.
The first is to exclude the category from the sync altogether using an `isIndexableCondition`.&#x20;
The second is to change the visibility sent in the data.

### Is Indexable Condition

:::hint{type="warning"}
Excluding the category this way would result in no products showing for this category on the frontend of your store for Category Navigation.
:::

To do this we inject an `isIndexableCondition` into the `isIndexableConditions` array for the virtual type `Klevu\IndexingCategories\Service\Determiner\IsIndexableDeterminer`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingCategoriess\Service\Determiner\IsIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="pageIsIndexableCondition"
                  xsi:type="object">Vendor\Module\Service\Determiner\CategoryIdIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>

```
:::

Create that class, which must implement the `IsIndexableConditionInterface`&#x20;

:::CodeblockTabs
Vendor/Module/Service/Determiner/CategoryIdIsIndexableCondition.php

```php
<?php

namespace Vendor\Module\Service\Determiner;

use Klevu\IndexingApi\Service\Determiner\IsIndexableConditionInterface;
use Magento\Catalog\Api\Data\CategoryInterface;


class CategoryIdIsIndexableCondition implements IsIndexableConditionInterface
{
    /**
     * Edit routes as required
     * Alternatively inject these via di.xml
     *
     * @param int[]
     */
    private array $excludedCategories = [
        4,
        23,
    ];
    
    public function execute(
        ExtensibleDataInterface|PageInterface $entity,
        StoreInterface $store,
    ): bool {
        if (!($entity instanceof CategoryInterface)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Invalid argument provided for "$entity". Expected %s, received %s.',
                    CategoryInterface::class,
                    get_debug_type($entity),
                ),
            );
        }
        
        return !in_array(
            needle: (int)$entity->getId(), 
            haystack: $this->excludedCategories, 
            strict: true,
        );
    }
}

```
:::

See [Entities Is Indexable Determiner](https://docs.klevu.com/klevu-magento-v4/entities-is-indexable-determiner) for more information.

### Change Visibility in the Synced Data

To change the data synced we must override the pipeline YAML for categories.

Create the override YAML file

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processCategory:
            stages:
              createRecord:
                stages:
                  attributes:
                    stages:
                      visibility: Vendor_Module::etc/pipeline/category/attributes/visibility.yml 
```
:::

Create the imported visibility YAML file.
It is possible to do this all in one YAML file, but separating it into multiple files makes it easier to read.
To remove all categories from search.

:::CodeblockTabs
Vendor/Module/etc/pipeline/category/attributes/visibility.yml&#x20;

```yaml
stages:
  -
    pipeline: Stage\StaticValue
    args:
      value: [""]
```
:::

To remove some categories from search. Take the current category and pass it into a transformer. This transformer should return an array of strings containing with   or `search`.

:::CodeblockTabs
Vendor/Module/etc/pipeline/category/attributes/visibility.yml&#x20;

```yaml
stages:
  -
    pipeline: Stage\Extract
    args:
      extraction: currentCategory::
      transformations: 
        - ToVisibility
```
:::

Create the transformer to handle the visibility

:::CodeblockTabs
Vendor/Module/Pipeline/Transformer/ToVisibility.php

```php
namespace Vendor\Module\Pipeline\Transformer;


use Klevu\Pipelines\Transformer\TransformerInterface;
use Magento\Catalog\Api\Data\CategoryInterface;


class ToVisibility implements TransformerInterface
{
    /*
     * @return string[]
     */
    public function transform(
        mixed $data,
        ?ArgumentIterator $arguments = null,
        ?\ArrayAccess $context = null,
    ): array {
    
    if (!($data instanceof CategoryInterface)) {
        throw new InvalidInputDataException(
            transformerName: $this::class,
            expectedType: CategoryInterface::class,
            arguments: $arguments,
            data: $data,
        );
    }
    
    return $this->visibilityProvider->get(
        category: data,
    );
}
```
:::

If you create a transformer in a custom module it must be registered with the pipelines before it can be used. See [Registering Transformers](https://docs.klevu.com/klevu-magento-v4/entities-registering-transformers) for more information.

Alternatively we could add an attribute to the category for visibility and use that instead of a transformer. e.g.&#x20;

:::CodeblockTabs
Vendor/Module/etc/pipeline/category/attributes/visibility.yml&#x20;

```yaml
stages:
  -
    pipeline: Stage\Extract
    args:
      extraction: currentCategory::getVisibility()

```
:::

Assumes `getVisibility` would return either   or `search`. If it returned an integer then we'd have to map that. see the visibility YAML for products `module-m2-indexing-products/etc/pipeline/product/attributes/visibility.yml`

See [Pipeline Customisation](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation) for more information on how to customise pipelines.

[title] Indexing Overview
[path] Indexing/

Klevu’s Magento modules use [Klevu’s Data Indexing JSON API](https://docs.klevu.com/indexing-apis) to register attributes and index entities with Klevu.

:::hint{type="warning"}
Before entity data for an attribute can be indexed to Klevu, the attribute **MUST** be registered with Klevu.

Some standard attributes do not require registration with Klevu, e.g. name, price, SKU. See [Indexing - Attributes](https://docs.klevu.com/klevu-magento-v4/attributes) for more details.
:::

### Module Structure

The Indexing module `module-m2-indexing` enables the indexing of attributes and entities to Klevu. The indexing module creates a skeleton for other indexing modules to inject data into.&#x20;
The indexing module itself has no knowledge of attribute or entity types. The entities Categories, CMS Pages and Products are added via their own modules `module-m2-indexing-categories`, `module-m2-indexing-cms` and `module-m2-indexing-products`. Merchants can also add their own modules to index any custom entity types.

### Removing modules

If you do not wish to index all entity types (products, categories, CMS pages) to Klevu you may remove the modules for those solutions by updating your `composer.json`

**Remove Indexing Categories**

```json
"replace": {
    "klevu/module-m2-indexing-categories": "*"
},
```

**Remove Indexing Cms Pages**

```json
"replace": {
        "klevu/module-m2-indexing-cms": "*"

},
```

**Remove Indexing Products**

```json
"replace": {
    "klevu/module-m2-indexing-products": "*"
},
```

If you are indexing data to Klevu via some other method (e.g. XML shopping feed) then you can remove all Klevu indexing modules.

```shell
composer remove "klevu/module-m2-indexing"
```

## Logging

The Indexing group of modules implement dedicated logs to segregate them from other areas, grouped by store name. These logs are found at `/var/log/klevu/[store_code]/klevu-[store_code]-indexing.log`.

To control the level of detail included in indexing logs (configurable on a store-by-store basis), please use the **Klevu** > **Developer Settings** > **Logging** > **Indexing Log Level** setting. See [Logging](https://docs.klevu.com/klevu-magento-v4/logging) for more information.

[title] Cumulative Layout Shift Facade/Placeholder
[path] Frontend/Theme JS/

Suggestions on how to best handle CLS can be found in our [knowledge base](https://docs.klevu.com/template-js/lighthousepagespeed).

## SRLP and Category Navigation

When Klevu Theme JS is used for Search Results Landing Page and/or Category Navigation the content is loaded from Klevu after the page has loaded. This can cause layout shifts and affect your page speed insights scores.&#x20;

To mitigate this layout shift we have added CSS to create an area where this content will be loaded. This works out of the box with the default theme, however, it will likely require changes if you customise the theme.

```css
.klevuLanding {min-height: 921px;}
@media (max-width: 1100px) {
  .klevuLanding {min-height: 1145px;}
}
@media (max-width: 900px) {
  .klevuLanding {min-height: 1695px;}
}
@media (max-width: 767px) {
  .klevuLanding {min-height: 2249px;}
}
@media (max-width: 480px) {
  .klevuLanding {min-height: 4228px;}
}
```

This is injected into the phtml files for both SRLP and Category Navigation via a container.

`module-m2-frontend-search/view/frontend/templates/search/results.phtml`
`module-m2-frontend-categorynavigation/view/frontend/templates/category.phtml`
These values work with the default templates, however, you will likely wish to adjust these values especially if you have customised the layout or added extra attributes as facets.

The CSS added is easy to remove and replace with your own via layout XML.&#x20;

:::CodeblockTabs
Vendor/Module/view/frontend/layout/klevu\_category\_index.xml

```xml
<referenceContainer name="klevu_frontend_category_navigation.category_container">
    <!-- Remove Klevu CLS block -->
    <block name="klevu_frontend_category_navigation.category_index_cls" remove="true"/>
    <!-- Inject your own block, if required -->
    <block name="vendor_module.klevu.category_index_cls"
           template="Vendor_Module::klevu/category-index-cls.phtml"/>
</referenceContainer>
```
:::

:::CodeblockTabs
Vendor/Module/view/frontend/layout/klevu\_search\_results.xml

```xml
<referenceContainer name="klevu_frontend_search.search_results_container">
    <!-- Remove Klevu CLS block -->
    <block name="klevu_frontend_search.search_results_cls" remove="true"/>
    <!-- Inject your own block, if required -->
    <block name="vendor_module.klevu.search_results_cls"
           template="Vendor_Module::klevu/category-index-cls.phtml"/>
</referenceContainer>
```
:::

Examples given of how to do this in a module. These changes could alternatively be made in your theme(s).

## Recommendations Banners

We also set a minimum height for the recommendations banner widgets. This is not added inside the widget as this could lead to duplication of code if there are multiple widgets on the page. We add this to the `Klevu_Frontend.before.body.end` container.

The CSS added is easy to remove and replace with your own via layout XML.&#x20;

:::CodeblockTabs
Vendor/Module/view/frontend/layout/default.xml

```xml
<referenceContainer name="Klevu_Frontend.before.body.end">
    <!-- Remove Klevu CLS block -->
    <block name="klevu_frontend_recommendations.recommendations_widget_cls" remove="true"/>
    <!-- Inject your own block, if required -->
    <block name="vendor_module.klevu.recommendations_widget_cls"
           template="Vendor_Module::klevu/recommendations-widget-cls.phtml"/>
</referenceContainer>
```
:::

Example given of how to do this in a module. This change could alternatively be made in your theme(s).


[title] Preparation
[path] Installation & Integration/

:::hint{type="warning"}
Please ensure you have read the installation **and** integration guides before beginning the process.&#x20;
:::

## Installation

:::hint{type="info"}
In line with Magento's best practice, we recommend taking a backup of your database and enabling maintenance mode before making any changes to your Magento site.

All changes should be tested in a non-production environment first.
:::

See [Magento guide on installation of third-party extensions](https://experienceleague.adobe.com/en/docs/commerce-operations/installation-guide/tutorials/extensions).&#x20;

You are free to install it from Packagist or Magento Marketplace. New versions will be released to Packagist first, with a delay in releasing to Marketplace due to the review processes. This delay could be several weeks.

:::hint{type="warning"}
It is not possible to install v2.x/v3.x and v4.x at the same time. Any attempt to install v4.x while v2.x/v3.x is installed will fail and display a warning message.&#x20;
i.e. running `composer require klevu/module-m2-search`&#x20;
before running `composer remove "klevu/*"` will fail.
:::

## Integration

There are steps you may wish to take before integrating your API keys.&#x20;

After you save your API keys the Klevu module will discover all your attributes, determine, which must be registered with Klevu and register them via the API. Klevu determines which attributes to sync via the `Register with Klevu` setting on each attribute. You may want to set these before integration. If you do not they will be picked up during the next cron run after integration. See [Indexing - Attributes](https://docs.klevu.com/klevu-magento-v4/attributes) for more information on this setting.

:::hint{type="info"}
We recommend creating a data patch to implement these changes on installation in your production environment.
:::




[title] Sync Orders
[path] Analytics/

# Sending Order Information to Klevu

Order analytics are sent to [the analytics collect service](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR); this is the same endpoint used for client-side analytics in earlier versions of the module, and replaces [the product tracking service](https://docs.klevu.com/apis/search-events#-2qMT) previously used for server side processing.

When a sync is initiated, all eligible orders are retrieved and passed through an ETL pipeline which converts and sends the data to Klevu’s analytics services. Unsuccessful orders are re-queued to be retried on future pipeline executions.

## Interfaces

Sync can be initiated via two methods, both of which are interfaces to the same pipeline process.

### Automatically via Cron

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, order sync cron tasks use the dedicated klevu group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

The `klevu_analytics_sync_orders` cron job runs every 5 minutes by default, though this is customisable via the global config setting **Klevu** > **Data Sync** > **Order Analytics&#x20;**> **Order Sync Frequency**. To ensure that orders can be reliably associated with the user session which triggered them we recommend this value is no more infrequent than every half hour.

Each time a cron job runs, it will attempt to process all queued orders (including retries) from sync enabled stores `*` across your installation. Orders are processed from oldest to most recent, regardless of sync status or the store on which the order was placed.

### Manually via Command Line

Order sync can also be triggered via the `klevu:analytics:sync-orders` CLI command. Executing via the terminal provides more control over the orders to be synced, allowing you to define a list of order ids and/or store ids to handle. Note that even if order ids are provided, only queued orders (including retries) will be processed - to resend a synced or stuck order, you must manually requeue it before processing.

By default, only sync enabled stores \* are processed, even where store ids are explicitly passed, however this check can be bypassed with the `--ignore-sync-enabled-flag` option.

Another subtle difference with the cron process is that the console command will attempt to process all failed orders (ie, those with a `retry` status) first, before moving onto new orders.

:::hint{type="info"}
\* The extension defines a “sync enabled store” by the following criteria

- The store is active in Magento
- The store is integrated with Klevu (ie, API keys have been saved for the store view)
- The config setting **Klevu** > **Data Sync** > **Order Analytics** > **Order Sync Enabled** is set to “Enable” for this store
:::

## Process

Execution of order sync is handled by a virtualType of the ProcessEvents service from the general Analytics module. This virtualType (defined as `Klevu\AnalyticsOrderSync\Service\ProcessOrderEvents`) uses Order Analytics services to provide context and payload data to the pipeline, as well as defining a dedicated `sync_orders.yml` pipeline configuration file. See `klevu/php-pipelines` documentation for more information  on defining pipeline objects.

The initial pipeline payload is provided by `\Klevu\AnalyticsOrderSync\Service\Provider\OrderSyncEventsDataProvider::get()`, a [Generator](https://www.php.net/manual/en/language.generators.overview.php) method yielding Magento Order objects based upon the search criteria provided by the calling interface (see above).&#x20;
In addition to order ID; store ID; and sync status filtering, if a value has been added to **Klevu** > **Data Sync** > **Order Analytics** > **Exclude Statuses From Sync**, that restriction will be applied at this stage. This setting can be defined at a store scope.

:::hint{type="info"}
Each order is sent in an individual API request to Klevu as the user profile information, which contains a customer’s email and IP address, is defined at an event level and not at an item level.
Ref: [Search Events - Storefront APIs](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR)&#x20;
:::

&#x20;While each order is processed and transmitted to Klevu individually, batching of records for process is still performed in the interface, with each batch size controlled by the **Klevu** > **Developer Settings** > **Order Analytics** > **Order Sync Max Batch Size** configuration value (*known issue in beta-1*). By default this value is 250. Batching records here mitigates performance concerns with large queues, while also ensuring that later records are less likely to be outdated during long processing runs.

While each order is processed and transmitted to Klevu individually, batching of records for process is still performed in the interface, with each batch size controlled by the **Klevu** > **Developer Settings** > **Order Analytics** > **Order Sync Max Batch Size** configuration value (

The order batch is handed off to the analytics pipeline (as defined at `etc/pipeline/sync_orders.yml`), where each undergoes a serious of transformations before being sent to Klevu’s analytics endpoints.

Some key stages are outlined below

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/X6cC7LmZ6PHYof7SOulAl_f65f9d84-baa0-4617-b2f9-82b2c25b8345.jpeg)

 

**Receive Payload**

A collection of orders is passed to the pipeline

**Iterate Payload**

The orders are looped though, to allow each order to be processed individually

**Mark Order As Processing**

The order record in `klevu_sync_order` is updated to have a status of “processing” and its attempts value (the number of times the order has passed through the pipeline) incremented.
This action will lock the order to prevent it being processed again if a second sync is run in parallel.

**Inject Line Items For Grouped Products**

Magento stores grouped product purchases as individual line items but, unlike configurable products, does not include a consolidated parent line item. As grouped products are indexed as single entities, we inject a spoof item into the payload for any grouped products purchased in the order.

**Filter Invalid Order Line Items**

Configurable products (the consolidated parent item) are removed, as Klevu indexes variants as individual records.
Child items of Grouped and Bundle products are removed, as Klevu indexes these product types as a single record.

**Iterate Line Items**

The order lines are looped through, allowing each item to be processed individually.

**Convert to Analytics Collect Event Object Ready For Send**

The converted order lines array is injected into an Event object (ref klevu/php-sdk) along with the Klevu API Key; customer information; event type; and event version.

**Send Analytics Event Data to Klevu API**

The consolidated data is sent as a JSON to the Klevu analytics/collect endpoint and the response received and passed along the pipeline.

**Mark Order As Processed Or Requeue**

Based on the API response in the previous stage, the record in `klevu_sync_order` is either updated to a “complete” status or, on error, moved to “retry” (if it has not yet passed the maximum retries threshold - see below) or “error” otherwise.

Once all records in the payload have been processed, the pipeline returns an object containing the result of each order processed.

### Handling Failures

Order records may not pass through the pipeline successfully for a variety of reasons, including invalid source data; system exceptions during transformation; or errors communicating with Klevu’s APIs. In all but exceptional circumstances, individual order failures will not stop the pipeline continuing with subsequent records in the payload.

Records which fail in a predictable way will be marked for retry (a status which is treated as queued when payloads are generated) and picked up the next time. Records which fail after sync has been attempted the maximum number of times (as defined by the **Klevu** > **Developer Settings** > **Order Analytics** > **Order Record Max Sync Attempts** config value) will instead be set to an “error” status and will not be picked up again unless manually re-queued.

:::hint{type="info"}
It is possible to re-queue orders which have exceeded the maximum sync attempts using the `klevu:analytics:queue-orders-for-sync` CLI command. The number of attempts counter will continue incrementing for this record.
:::

### “Stuck” Records

While looping through record in the pipeline, the order’s sync status is set the “processing”. This informs administrators and the system alike that this record is currently undergoing transformation and sync.

If the pipeline exits unexpectedly before the record finishes processing and has its status updated a second time, the record can never be picked up for retry. While these orders can be re-queued manually using the `klevu:analytics:queue-orders-for-sync` CLI command, they will be automatically moved into a “retry” status after a 15 minute threshold (configurable using the **Klevu** > **Developer Settings** > **Order Analytics** > **Consider Processing Orders Stuck After (minutes)** setting).&#x20;

This action is performed by the `klevu_analytics_requeue_stuck_orders` cron task, which is scheduled to run on the hour. This means that records may be stuck for up to 75 minutes, depending on the last processing time, before being requeued.

### Extracting Order IP Address

Magento may store multiple IP addresses against a single order, either within the same field or in different fields depending on what data is being stored (such as when WAF or CDNs are used).

The pipeline stage `processOrders.iterateOrders.processOrder.execute.extractEventData.createUserProfile.createRecord.ip_address` uses a dynamic extractor set within the Context object, which uses the **Klevu** > **Developer Settings** > **Order Analytics&#x20;**> **IP Address Field for Order Data** configuration setting to toggle between the `remote_ip` and `x_forwarded_for` fields.

In cases where multiple IPs are saved within the same field, the pipeline will use the first one found in a comma-separated list.

## Duplicate Records

A concern with automatically re-queueing orders in a processing status is that duplicate data will be sent to Klevu, affecting conversion rate information.

While it is possible for the same order to be submitted multiple times (whether through stuck record re-queueing, or manual sync), the Klevu services receiving this data will filter duplicate records based upon the unique combination of Magento order and order line ids.

[title] Is Indexable Determiner
[path] Indexing/Entities/Discovery/

## Determiners & Conditions

If an entity is indexable is determined by `Klevu\Indexing\Service\Determiner\IsIndexableDeterminer`
This determiner loops through all injected `Klevu\IndexingApi\Service\Determiner\IsIndexableConditionInterface` classes.
If **any** of these return false; then the entity is set to **not indexable** and will not be indexed with Klevu.&#x20;
If they **all** return true; then the entity is indexable and can be indexed with Klevu.

All entity types `module-ms-indexing-categories`, `module-ms-indexing-cms` and `module-m2-indexing-products` create virtualTypes of this class and inject an array of conditions.
e.g. for products the virtualType in `di.xml` looks like this

:::CodeblockTabs
module-m2-indexing-products/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Determiner\IsIndexableDeterminer"
             type="Klevu\Indexing\Service\Determiner\IsIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="disabledProductsIsIndexableCondition"
                  xsi:type="object">Klevu\IndexingProducts\Service\Determiner\DisabledProductsIsIndexableCondition</item>
            <item name="oosProductsIsIndexableCondition"
                  xsi:type="object">Klevu\IndexingProducts\Service\Determiner\OutOfStockProductsIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>
```
:::

***

## Custom Conditions

You can add conditions to amend the default behaviour.
Let's say you only wanted to index products when the attribute `color` was `pink`.
You’d inject your condition in to the `IsIndexableDeterminer` via the `isIndexableConditions` array in your `di.xml`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Determiner\IsIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="pinkProductIsIndexableCondition"
                  xsi:type="object">Vendor\Module\Service\Determiner\PinkProductIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create that class, which must implement the `IsIndexableConditionInterface`&#x20;

:::CodeblockTabs
Vendor/Module/Service/Determiner/PinkProductIsIndexableCondition.php

```php
<?php

namespace Vendor\Module\Service\Determiner;

use Klevu\IndexingApi\Service\Determiner\IsIndexableConditionInterface;

class PinkProductIsIndexableCOndition implements IsIndexableConditionInterface
{
    public function execute(
        ExtensibleDataInterface|PageInterface $entity,
        StoreInterface $store,
    ): bool {
        if (!($entity instanceof ProductInterface)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Invalid argument provided for "$entity". Expected %s, received %s.',
                    ProductInterface::class,
                    get_debug_type($entity),
                ),
            );
        }
        
        return $entity->getAttributeText('color') === 'pink';
    }
}

```
:::

See `Klevu\IndexingProducts\Service\Determiner\DisabledProductsIsIndexableCondition` as an example of a determiner condition.

[title] Installation
[path] Installation & Integration/New Installation of v4.x/

:::hint{type="danger"}
If you're an existing customer using Klevu module versions v2.x or v3.x, migration to v4.x is not currently supported. However, we encourage you to contact [support ](https://help.klevu.com/support/tickets/new)and express your interest. We'll notify you via email once the migration option becomes available.
:::

:::hint{type="warning"}
In line with Magento's best practice, we recommend taking a backup of your database and enabling maintenance mode before making any changes to your Magento site.

All changes should be tested in a non-production environment first.
:::

## Step 1 - Add v4.x packages

Add the modules via composer.&#x20;

```shell
composer require "klevu/module-m2-search:^4.0.0"
```

## Step 2 - Update Magento

Enable modules, update the database, compile code, generate static content and clear caches.

```shell
bin/magento module:status | grep Klevu_ | grep -v List | grep -v None | grep -v -e '^$'| xargs php bin/magento module:enable
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy
bin/magento cache:flush
```

##


[title] Sync History
[path] Indexing/Entities/Sync/

## Product Grid

The Indexing Products module adds a new action to the product grid `Klevu Sync Info`. Selecting this action will open a modal containing information on the sync status and history of that product.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/NlF1i4qEbmpKk3cHAQsQw_screenshot-2024-09-23-at-181951.png "Product Grid")

## Next Sync Actions

Shows the previous and next actions for product sync for each API key.
Simple products that are also configurable variants will have an entry per configurable they are part of as well as an entry for the standalone simple product.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/MP921jO5PWYhsHtdgXcDb_screenshot-2024-09-23-at-182000.png "Next Sync Actions")

## Sync History (Today)

Shows all sync actions taken today for this product. The API key the action took place for. What type of action was taken `Add`, `Update` or `Delete`. If that action was successful and records the response from the API.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/ktO_s0klhX3HxBU334eQS_screenshot-2024-09-23-at-182017.png "Sync History (Today)")

## Sync History (Previous Days)

Sync history is consolidated nightly via cron. The days actions are saved as a JSON object. The actions for each day can be viewed in this table.

### Removing Sync History

Sync history is removed after a number of days via cron. This is set to 7 days by default and can be configured in the admin `Stores > Configuration > Klevu > Developer Settings > Indexing > Remove History For Indexing After (days)`. The path in `core_config_data`is `klevu/indexing/remove_indexing_history_after_days`

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/tlPL9eaj8qmRqrZIqIrjd_screenshot-2024-09-26-at-151850.png "Remove Sync History")

### Cron Setup

**Consolidate History**

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_history_consolidation"
     instance="Klevu\Indexing\Cron\SyncHistoryConsolidation"
     method="execute">
    <schedule>2 0 * * *</schedule>
</job>
```
:::

**Remove History**

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_history_consolidation_clean"
     instance="Klevu\Indexing\Cron\SyncHistoryConsolidationClean"
     method="execute">
    <schedule>10 0 * * *</schedule>
</job>
```
:::






[title] Indexing
[path] /

## Overview

The Indexing module enables the indexing of attributes and entities to Klevu. The module creates a skeleton for other indexing modules to inject data into. The indexing module itself has no knowledge of attribute or entity types. Categories, CMS Pages and Products are added via their own modules `module-m2-indexing-categories`, `module-m2-indexing-cms` and `module-m2-indexing-products`. Merchants can also add their own modules to index any custom entity types.

:::hint{type="warning"}
Before entity data for an attribute can be indexed to Klevu, the attribute **MUST** be registered with Klevu.
:::

Some standard attributes do not require registration with Klevu, e.g. name, price, SKU. See [Indexing - Attributes](https://app.archbee.com/docs/8cIJaE_9UAmWKNnQcRcUb/rAZcadVJRDbfEgoouhqQ4) for more details.

Klevu’s Magento modules use [Klevu’s Data Indexing JSON API](https://docs.klevu.com/indexing-apis) to register attributes and index entities with Klevu.

## Logging

The Indexing group of modules implement dedicated logs to segregate them from other areas, grouped by store name. These logs are found at /var/log/\[store\_code]/klevu-\[store\_code]-indexing.log.

To control the level of detail included in indexing logs (configurable on a store-by-store basis), please use the **Klevu** > **Developer Settings** > **Logging** > **Indexing Log Level** setting. See [Logging](https://app.archbee.com/public/PREVIEW-8cIJaE_9UAmWKNnQcRcUb/PREVIEW-E-LF1vzErUXZienZHDNx-) for more information.


[title] Entities
[path] Indexing/

## What is an Entity?

We define an entity as a Category, CMS page or Product. Merchants can also add their own modules to index any custom entity types.

## JSON API

[Klevu’s Data Indexing JSON API](https://docs.klevu.com/indexing-apis/swaggeropenapi-specification) is used to index all entity data.

## Database

Upon installation, the Klevu module will create a database table `klevu_indexing_entity` to maintain the status of all entities. This database is automatically populated via entity discovery (run via cron 5 minutes after account integration). This database table is updated whenever relevant entity data is changed. e.g. a name change or an entity is enabled/disabled. These changes will update the `next_action` column. The `next_action` will be set to either  , `Add`,  `Update` or `Delete`. This column defines what will happen during the next sync.

## Admin Stores Configuration Settings

Indexing for each entity type can be controlled in the admin. Navigate to `Stores > Configuration > Klevu > Data Sync` under the Indexing tab you’ll see the following settings to enable/disable indexing for each entity type. You can also set the height and width of the images indexed to Klevu.

:::hint{type="warning"}
By default, Klevu will index all enabled entities, even if they are out of stock or not visible individually.
:::

| **Klevu** > **Data Sync** > **Indexing** | **Scope**                               |                                                                                                       |
| ---------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Enable Category Sync                     | Enable Category Sync<br />\[store view] | Controls whether to index category data to Klevu. Default value “Yes”.                                |
| Enable CMS Sync                          | \[store view]                           | Controls whether to index CMS Page data to Klevu. Default value “Yes”.                                |
| Enable Product Sync                      | \[store view]                           | Controls whether to index product data to Klevu. Default value “Yes”.                                 |
| Product Image Width                      | \[store view]                           | Determines the width of the images generated before indexing the link to Klevu. Default value “130”.  |
| Product Image Height                     | \[store view]                           | Determines the height of the images generated before indexing the link to Klevu. Default value “130”. |



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/UqeawM8r5Vq3188X53w2m_screenshot-2024-03-26-at-095223.png "Stores > Configuration > Klevu > Data Sync > Indexing")

There are further indexing settings located `Stores > Configuration > Klevu > Developer Settings`. These settings enable you to control if Entity status or stock levels should be considered when adding or removing an entity from indexing.

| **Klevu** > **Developer Settings** > **Indexing - CMS** | **Scope** |                                                                                           |
| ------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------- |
| Exclude Disabled CMS Pages                              | \[global] | Controls whether to exclude disabled CMS pages from the Klevu index. Default value “Yes”. |

| **Klevu** > **Developer Settings** > **Indexing - Products** | **Scope** |                                                                                             |
| ------------------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------- |
| Exclude Disabled Products                                    | \[global] | Controls whether to exclude disabled products from the Klevu index. Default value “Yes”.    |
| Exclude Out of Stock Products                                | \[global] | Controls whether to exclude out of stock products from the Klevu index. Default value “No”. |

| **Klevu** > **Developer Settings** > **Indexing - Categories** | **Scope** |                                                                                            |
| -------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------ |
| Exclude Disabled Products                                      | \[global] | Controls whether to exclude disabled categories from the Klevu index. Default value “Yes”. |



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/EiAbj2IAl5Q1--hl73xMG_screenshot-2024-03-26-at-095254.png "Stores > Configuration > Klevu > Developer Settings > Indexing")


[title] Recommendation Widgets
[path] Frontend/

Magento Enterprise Edition (Adobe Commerce) has a feature called Dynamic Blocks. These blocks are not present in Magento’s full page cache, they are rendered after a page load and can be used to show blocks only to certain customer groups. This caused issues with recommendations as the javascript had already fired before these blocks loaded, causing them not to render.

When adding 2 recommendation banners to the same page often the second will not render as the first banner causes Klevu's javascript to fire before it is aware of the second.

To avoid these issues, rather than merchants entering the following to create the recommendations banner

```html
<div class="klevu-recs" id="k-c1389f6c-a895-496c-995a-d69f7fe0e6cb"></div>

```

this has to be changed to

```html
<div class="klevu-recs" id="k-c1389f6c-a895-496c-995a-d69f7fe0e6cb" data-bind="afterRender: function(recsTargetElement) {
    if ('undefined' !== typeof klevu && 'undefined' === typeof recsTargetElement.recsObject) {
        let myRecsbox = klevu.recs.clone({
            recId: recsTargetElement.id,
            apiKey: klevu.getGlobalSetting('recs.apiKey', klevu.getGlobalSetting('global.apiKey')),
            element: recsTargetElement
        });
        myRecsbox.powerUp();
    }
}"></div>

```

The first div loads content faster, but may not work in every scenario. The second div will always work, but loads the recommendations banner after the page is rendered.

The manual approach to adding these banners can still be taken, however we have created a widget to add recommendations to the site that will handle this.

To add a recommendations widget (there are other ways, this is just one example):

- Login to the Admin
- Navigate to `Content > Elements > Widget`
- Click `Add Widget`
- From the `Type` dropdown select `Klevu Recommendations`.
- From the `Design Theme` dropdown select your theme.
- Click `Continue`
- Enter a `Widget Title`
- Enter `Sort Order` (optional)
- Set `Layout Update` - i.e. where the widget will appear.
- Click the `Widget Options` tab.
- Enter your `Klevu Recommendations ID` e.g. `k-a123b45c-copy-this-code-6789d01e23f4`
- Enter a `Block Title` (optional). You can add titles in KMC, however this enables a merchant to use the same banner with different titles on different pages/stores.
- Select if this widget `Requires Power Up`. (`Yes`: will add the extended code above that will work everywhere. `No`: will add the single line of HTML, loads faster, but may not work in every situation)
- Click `Save`

:::hint{type="info"}
A cache flush may be required to see the output on the frontend.
:::

:::hint{type="warning"}
If you experience any issues with recommendation banners not loading as expected try switching `Requires Power Up` to `Yes`
:::


[title] Using Text Attributes as Klevu Facets
[path] Common Customisations/

The Klevu Indexing functionality respects and uses core Magento settings wherever possible. When defining Klevu attributes from Magento data, we reference the “Use In Layered Navigation” field when setting the Filterable property. Unfortunately, there are types of Magento attributes which cannot be defined for use in layered navigation which are still valid Klevu facets - for example, Text attributes (as Klevu generates its own enumerated index as part of the indexing process)

![Example of Magento select field attribute](https://archbee-image-uploads.s3.amazonaws.com/txIf3IazdJsdQky_oYUyV-FTCoobEYRbZSCUqwIKU6b-20250716-124046.png "Select Attribute")

![Example of Magento text field attribute](https://archbee-image-uploads.s3.amazonaws.com/txIf3IazdJsdQky_oYUyV-FyH-zJqsieqeCTAxgNtcu-20250716-124201.png "Text Attribute")

Where changes to automatically populated Klevu attribute properties is required, we need to extend the core Klevu functionality with a small bespoke module.

:::hint{type="info"}
These changes can also be incorporated into existing customisation modules, though we recommend keeping customisations separate to allow easier maintenance, debugging, and removal if required.
:::

## Building The Extension

:::hint{type="info"}
This guide assumes you are familiar with creating a Magento 2 extension.

If you work better with code in front of you to reference, there is an example module at the end of the article
:::

:::hint{type="warning"}
**IMPORTANT**
This example module is not production-ready and should not be used. It is for reference and illustration purposes only and no guarantee is made to its reliability.

We strongly recommend testing it in your own environment before deploying it to production.
:::

We will use the module name `Vendor_KlevuIndexingAttributeDefinitions`; you should choose a namespace (and module name) suited to your installation.

### Dependencies

We will reference the **Klevu Indexing Products** and **PHP-SDK** packages, so ensure you include the following in the extension’s `composer.json` file

:::CodeblockTabs
composer.json

```json
    "require": {
        "php": "~8.1.0|~8.2.0|~8.3.0|~8.4.0",
        "klevu/module-m2-indexing-products": "^3.0.0",
        "klevu/php-sdk": "^1.1.0"
    },
```
:::

and the following in the extension’s `etc/module.xml` file

:::CodeblockTabs
etc/module.xml

```xml
        <sequence>
            <module name="Klevu_IndexingProducts"/>
            <module name="Klevu_PhpSDK"/>
        </sequence>
```
:::

### Overriding the Attribute Definition

To implement our changes, we need to modify the `Klevu\IndexingProducts\Service\AttributeIndexingRecordCreatorService` return; this is the service responsible for converting a Magento EAV Attribute into an object which can be used by the SDK to register attributes in Klevu.

*Reference:&#x20;*[klevu/module-m2-indexing-products](https://github.com/klevu/module-m2-indexing-products/blob/main/Service/AttributeIndexingRecordCreatorService.php#L67)**

We’re simply going to take the SDK Attribute and update its properties before it’s used by other parts of the system. As such, we need to add an after plugin on the execute method, using the following di.xml code (while you could add this to the adminhtml area, it’s safest to add it globally to ensure future compatibility)

```xml
    <type name="Klevu\IndexingProducts\Service\AttributeIndexingRecordCreatorService">
        <plugin name="Vendor_KlevuIndexingAttributeDefinitions::IndexingProducts_UpdateAttributeDefinitionPlugin"
                type="Vendor\KlevuIndexingAttributeDefinitions\Plugin\IndexingProducts\Service\AttributeIndexingRecordCreatorService\UpdateAttributeDefinitionPlugin"/>
    </type>
```

Our plugin will then need an `afterExecute` method to receive and modify the data; that class' skeleton should look something like

:::CodeblockTabs
Plugin/.../UpdateAttributeDefinitionPlugin.php

```php
<?php

/**
 * This is a demonstration module provided by Klevu with no guarantees, active support, or planned updates
 * It should be used as a base to create your own extension implementing the specific functionality
 *  required for your installation, rather than being directly installed as an out-of-the-box solution
 */

declare(strict_types=1);

namespace Vendor\KlevuIndexingAttributeDefinitions\Plugin\IndexingProducts\Service\AttributeIndexingRecordCreatorService;

use Klevu\IndexingProducts\Service\AttributeIndexingRecordCreatorService;
use Klevu\PhpSDK\Api\Model\Indexing\AttributeInterface as SdkAttributeInterface;
use Magento\Eav\Api\Data\AttributeInterface;

class UpdateAttributeDefinitionPlugin
{
    /**
     * @param AttributeIndexingRecordCreatorService $subject
     * @param SdkAttributeInterface $result
     * @param AttributeInterface $attribute
     * @param string $apiKey
     *
     * @return SdkAttributeInterface
     */
    public function afterExecute(
        AttributeIndexingRecordCreatorService $subject,
        SdkAttributeInterface $result,
        AttributeInterface $attribute,
        string $apiKey, // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
    ): SdkAttributeInterface {
        // Your modifications here

        return $result
    }
}

```
:::

Unless you want to change every registered attribute (bad idea), you will need a way of identifying which attribute you are currently dealing with. The easiest and most reliable way is to use the Magento attribute code, available via the `$attribute variable`; eg

```php
switch ($attribute->getAttributeCode()) {
    case 'my_text_attribute':
    case 'another_text_attribute':
        // changes here
        break;
}
```

Alternatively, you can retrieve the attribute code as it will be registered in Klevu (ie, what you see in KMC)

:::hint{type="warning"}
This value is usually the same as the Magento attribute code, however it will differ if mapping has been performed
*Reference:&#x20;*`Klevu\IndexingApi\Service\Mapper\MagentoToKlevuAttributeMapperInterface::get`*&#x20;called in&#x20;*`AttributeIndexingRecordCreatorService::getAttributeName`
:::

```php
switch ($attribute->getAttributeCode()) {
    case 'klv_text_attribute':
    case 'klv_text_attribute2':
        // changes here
        break;
}
```

To modify the SDK Attribute’s data (in this case, we will target the `filterable` property, but you can modify any SDK attribute property supported by the SDK), you need to set the value on `$return` prior to returning it back to the calling code.

:::hint{type="warning"}
While we *should* be able to rely on receiving an instance of the SDK Indexing Attribute model, we only stipulate the AttributeInterface which does not mandate setters for properties. As such, we should feature sniff before setting any values

*Reference:&#x20;*[Klevu\PhpSDK\Api\Model\Indexing\AttributeInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/AttributeInterface.php)**
:::

Example -*&#x20;preferred method*

```php
    public function afterExecute(
        AttributeIndexingRecordCreatorService $subject,
        SdkAttributeInterface $result,
        AttributeInterface $attribute,
        string $apiKey, // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
    ): SdkAttributeInterface {
        switch ($result->getAttributeName()) {
            case 'klv_text_attribute':
            case 'klv_text_attribute2':
                if (method_exists($result, 'setFilterable')) {
                    // You could log if the method doesn't exist, but that should be
                    //  pretty obvious during development
                    $result->setFilterable(true);
                }
                break;
        }

        return $return;
    }
```

If you are dealing with an implementation of the SDK AttributeInterface which does not have setters - including trying to set Attribute Name or Data Type on `Klevu\PhpSDK\Model\Indexing\Attribute` - you will need to replace `$return` with a new instance and return that instance.

Example 2 - *Alternative implementation, using setters is preferred*

```php
use Klevu\PhpSDK\Model\Indexing\Attribute as SdkAttribute;
use Klevu\PhpSDK\Model\Indexing\AttributeFactory as SdkAttributeFactory;
use Klevu\PhpSDK\Model\Indexing\DataType;

class UpdateAttributeDefinitionPlugin
{
    private readonly SdkAttributeFactory $attributeFactory;

    public function afterExecute(
        AttributeIndexingRecordCreatorService $subject,
        SdkAttributeInterface $result,
        AttributeInterface $attribute,
        string $apiKey, // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
    ): SdkAttributeInterface {
        switch ($result->getAttributeName()) {
            case 'klv_text_attribute':
            case 'klv_text_attribute2':
                $result = $this->attributeFactory->create(
                    data: [
                        // You can change any of the attributes used to register the attribute
                        SdkAttribute::FIELD_ATTRIBUTE_NAME => $result->getAttributeName(),
                        // including the data type
                        SdkAttribute::FIELD_DATATYPE => DataType::NUMBER,
                        // and just set any you don't wish to change to the existing value
                        SdkAttribute::FIELD_LABEL => $result->getLabel(),
                        SdkAttribute::FIELD_SEARCHABLE => false,
                        SdkAttribute::FIELD_FILTERABLE => true,
                        SdkAttribute::FIELD_RETURNABLE => $result->isReturnable(),
                        SdkAttribute::FIELD_ABBREVIATE => $result->isAbbreviate(),
                        SdkAttribute::FIELD_RANGEABLE => true,
                    ],
                );
                break;
        }
    }
}

```

And that should be all the required changes, and you can recompile your Magento installation.

At this point, the next time an attribute is modified and the Attribute Discovery process runs, your changes will be applied. You can force this by either changing something in the attribute in the Magento admin, or running an attribute update for all or some attributes via CLI.

For example, to update product attributes with *Magento* ids 1, 2, and 3 run

```bash
/var/www/html$ php bin/magento klevu:indexing:attribute-update --attribute-ids 1,2,3 --attribute-type KLEVU_PRODUCT
```

## Example Module

- [Vendor\_KlevuIndexingAttributeDefinitions on GitHub](https://github.com/klevultd/m2-customisations/tree/main/Vendor_KlevuIndexingAttributeDefinitions)

## Further Reading

- [Klevu Custom Attributes](https://docs.klevu.com/indexing-apis/custom-attributes) (Indexing APIs)
- [Registering Attributes that are not Magento Attributes](https://docs.klevu.com/klevu-magento-v4/indexing-registering-attributes-that-are-not-magento-attributes) (Klevu Magento v4)
- [Attributes](https://docs.klevu.com/klevu-magento-v4/attributes) (Klevu Magento v4)
- [Add, Update, or Delete Indexing Attributes](https://docs.klevu.com/php-sdk/add-update-delete) (Klevu PHP SDK)
- [Managing Attributes](https://docs.klevu.com/php-sdk/managing-attributes) (Klevu PHP SDK)






[title] Enabling and Disabling Features
[path] Frontend/

Enabling or disabling Quick Search, Search Results Landing Page, Category Navigation and Recommendations are all handled in the same configuration area.

`Stores > Configuration > Klevu > Frontend`

### Quick Search

**Enabled**

Options: `Yes / No`.
Enable or disable Klevu Quick Search on the frontend of your store.&#x20;
Store View scope setting.

### Search Result Landing Page

**Ordering & Rendering**

Options: `Native Magento / Klevu Theme`
Toggle between Magento’s native SRLP and Klevu J2 Theme SRLP.
Store View scope setting.

### Category Navigation

**Ordering & Rendering**

Options: `Native Magento / Klevu Theme`
Toggle between Magento’s native SRLP and Klevu J2 Theme SRLP.
Store View scope setting.

### Recommendations

**Enabled**

Options: `Yes / No`.
Enable or disable Klevu Recommendations on the frontend of your store.&#x20;
Store View scope setting.

### Pricing

**Display prices after Customer Group Load**

Options: `Yes / No`.
Enable or disable loading of prices for customer groups. When enabled this will return prices from Klevu for the current customer group. However, that customer group is not available in the Magento cache and has to be retrieved after page load resulting in a slight delay in page rendering. Disable this if you do not use customer group pricing.
Store View scope setting.

### Page Meta

**Enabled**

Options: `Yes / No`.
Enable or disable Page Meta ***when all other frontend Klevu settings are disabled***. If Quick Search, SRLP, Category Navigation or Recommendations are enabled then Page Meta will be included on the frontend no matter what this is set to.&#x20;
Store View scope setting.

:::hint{type="info"}
After changing any configuration settings, please remember to clear the Config cache.
:::


[title] Adding External Javascript
[path] Frontend/Theme JS/

Klevu adds external Javascript files to your site to enable Klevu Theme JS to work as expected. The core file is always added when any Klevu solution is enabled. Other files include Recommendations, Category Navigation, SRLP and Quick Search.

### Javascript required at load time

The majority of the files added by Klevu are required at load time and are added to the head via the Magento `secureRenderer` like so.&#x20;

:::CodeblockTabs
module-m2-frontend/view/frontend/templates/html/head/js\_includes.phtml

```php
<?php foreach ($viewModel->getLinks() as $id => $link): ?>
    <?= /* @noEscape */ $secureRenderer->renderTag(
        tagName: 'script',
        attributes: [
            'type' => 'text/javascript',
            'id' => $escaper->escapeHtmlAttr($id),
            'src' => $escaper->escapeUrl(string: $link),
        ],
        textContent: false,
    ) ?>
<?php endforeach; ?>
```
:::

### Javascript that can be deferred

Quick Search however is not required at load time and can be loaded after page load.

We have taken a lead from [Hyvä Themes](https://docs.hyva.io/hyva-themes/writing-code/patterns/loading-external-javascript.html#overview) with our approach here adding files to the head after load to avoid blocking the rendering of the page. e.g.

```javascript
const script = document.createElement('script')
script.src = 'https://www.example.com/render-blocking-script.js';
script.type = 'text/javascript';
document.head.append(script);
```

Our implementation can be found in this template file

:::CodeblockTabs
module-m2-frontend/view/frontend/templates/html/head/js\_includes\_defer.phtml

```php
<?php foreach ($viewModel->getLinks() as $id => $link): ?>
    <?php
    $scriptString = "
        var deferredScript = document.createElement('script');
            deferredScript.type = 'text/javascript';
            deferredScript.id = '{$escaper->escapeHtmlAttr($id)}';
            deferredScript.src = '{$escaper->escapeUrl(string: $link)}';
            document.head.append(deferredScript);
   ";
    ?>
    <?= /* @noEscape */ $secureRenderer->renderTag(
        tagName: 'script',
        attributes: [
            'type' => 'text/javascript',
            'id' => 'klevu_include_defer_' . $escaper->escapeHtmlAttr($id),
        ],
        content: $scriptString,
        textContent: false,
    ) ?>
<?php endforeach; ?>
```
:::

We loop through all provided links and add them to the head after page load.

Adding scripts to the head in this manner is better for performance however, it does not  add those scripts via secureRenderer. External scripts added from klevu.com are whitelisted via `etc/csp_whitelist.xml` in the relevant modules.

:::hint{type="info"}
Note: All Klevu scripts are removed from the checkout page by default.
:::

If you require those scripts to be added via the secureRenderer please ensure you inject quick search to the head using the first method.

Layout XML to make that switch:

:::CodeblockTabs
Vendor/Magento/view/frontend/layout/default.xml

```xml
<referenceContainer name="Klevu_Frontend.before.body.end">
    <!-- Remove Deferred Script -->
    <block name="Klevu_Frontend.js_includes_defer.search" remove="true"/>
    <!-- Add to Head on Page Load -->
    <block name="Klevu_Frontend.js_includes.search"
           template="Klevu_Frontend::html/head/js_includes.phtml"
           after="-">
        <arguments>
            <argument name="js_includes_view_model"
                      xsi:type="object">Klevu\FrontendSearch\ViewModel\Html\Head\JsIncludesQuick</argument>
            <argument name="escaper_view_model"
                      xsi:type="object">Klevu\Frontend\ViewModel\Escaper</argument>
        </arguments>
    </block>
</referenceContainer>

```
:::

The example given shows how to make this change in a module. Theses change could alternatively be made in your theme(s).

[title] Update
[path] Indexing/Entities/Discovery/

:::hint{type="warning"}
Entity update does not send any data via the API to Klevu.

Its only purpose is to update the `klevu_indexing_entity` database table and calculate the `next_action`.
:::


Entity Update triggers Entity Discovery for a selection of entity IDs.
Various plugins and observers trigger entity updates, e.g. when an entity is saved.

Entity update will:

- add any missing entities and determine if those entities are indexable.
- set any of the passed entity IDs which are no longer indexable, but were previously registered, to have a `next_action` of `Delete`.
- set any of the passed entity IDs that have become indexable to have a `next_action` of `Add`.
- set the `next_action` for the passed entity IDs to `Update` if they are indexable.

Entity update will **NOT**:

- send any data to Klevu.

`\Klevu\Indexing\Service\EntityUpdateOrchestratorService` responsible for entity update. All the above methods of triggering entity update use this service.

### CLI

`klevu:indexing:entity-update`

The update can also be triggered via CLI and has 1 required parameter and 2 optional parameters

- `entity-ids` - a comma-separated list of entity IDs to update
- `api-keys` - \[optional] comma-separated list of API keys to update
- `entity-types` - \[optional] comma-separated list of entity types to update,
  options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`

e.g

```shell
bin/magento klevu:indexing:entity-update \
    --entity-ids="1,2,3" \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" 

```


[title] Sync
[path] Indexing/Entities/

:::hint{type="info"}
Entity sync is responsible for sending entity data to Klevu.&#x20;

The type of API request depends on the `next_action` column in the `klevu_indexing_entity` database table. If that column is set to `Add` then an add request will be sent, if it is empty no request will be sent.
:::

Entity sync is triggered:

- via cron
- via CLI

`\Klevu\Indexing\Service\EntitySyncOrchestratorService` responsible for entity sync. All the above methods of triggering entity sync use this service.

### Cron

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, entity sync cron tasks use the dedicated `klevu` cron group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

Entity sync runs every 30 minutes by default. This can be configured in the Magento admin, `Stores > Configuration > Klevu > Data Sync > Indexing > Entity Indexing Sync Frequency`.
The default setting can be found here `module-m2-indexing/etc/config.xml`
The configuration for the cron can be found here `module-m2-indexing/etc/crontab.xml`

:::CodeblockTabs
module-m2-indexing/etc/crontab.xml

```xml
<job name="klevu_indexing_sync_entities"
     instance="Klevu\Indexing\Cron\SyncEntities"
     method="execute">
    <config_path>klevu/indexing/entity_cron_expr</config_path>
</job>
```
:::

### CLI

`klevu:indexing:entity-sync`

The sync can also be triggered via CLI and has 2 optional parameters

- `api-keys` - \[optional] comma-separated list of API keys to update
- `entity-types` - \[optional] comma-separated list of entity types to sync,
  &#x20;options:
  - `KLEVU_PRODUCT`
  - `KLEVU_CATEGORY`
  - `KLEVU_CMS`

Increasing the verbosity of the command will give you more information using `-v`, `-vv`, or `-vvv`

e.g

```shell
bin/magento klevu:indexing:entity-sync \
    --entity-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" \
    -vvv
```

### Data

If an attribute has been registered with Klevu for indexing that does not mean it is automatically sent to Klevu. It means it can be sent to Klevu.&#x20;

Entity data indexed to Klevu is defined in the [indexing pipelines](https://docs.klevu.com/klevu-magento-v4/entities-pipelines) YAML files.&#x20;
For custom attributes, you can either&#x20;

- enable autogeneration of the YAML files in the admin at `Stores > Configuration > Klevu > Developer Settings > Pipelines > Enable autogeneration of configuration overrides` and select the product types to send this data for in `Automatically Generate Pipeline Configuration For` section of the attribute properties.
- add your own YAML file for the attribute - see [pipelines customisation](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation)


[title] Entity Discovery
[path] Indexing/Entities/Custom Entity Types/

To sync any entities first we have to discover them. In order to discover entities for a new entity type we must inject an `EntityDiscoveryProvider` into the `EntityDiscoveryOrchestratorService`&#x20;
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Indexing\Service\EntityDiscoveryOrchestratorService">
    <arguments>
        <argument name="discoveryProviders" xsi:type="array">
            <item name="custom_types"
                  xsi:type="object">Vendor\Module\Service\Provider\CustomTypeEntityDiscoveryProvider</item>
        </argument>
    </arguments>
</type>

```
:::

That `CustomTypeEntityDiscoveryProvider` will be a virtual type of `Klevu\Indexing\Service\Provider\EntityDiscoveryProvider`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\CustomTypeEntityDiscoveryProvider"
             type="Klevu\Indexing\Service\Provider\EntityDiscoveryProvider">
    <arguments>
        <argument name="entityType" xsi:type="string">CUSTOM_TYPE</argument>
        <argument name="entityProviders" xsi:type="array">
            <item name="custom_type"
                  xsi:type="object">Vendor\Module\Service\Provider\CustomTypeEntityProvider</item>
        </argument>
        <argument name="isIndexableDeterminer"
                  xsi:type="object">Vendor\Module\Service\Determiner\IsIndexableDeterminer</argument>
    </arguments>
</virtualType>

```
:::

:::hint{type="warning"}
While `CUSTOM_TYPE` can be any string as long as it does not clash with any existing types, we advise you do not begin the string with `KLEVU_`. If we add more types in the future and they will begin `KLEVU_` which could cause a name clash.
:::

Create the `CustomTypeEntityProvider` which must implement `Klevu\IndexingApi\Service\Provider\EntityProviderInterface`

```php
class CustomTypeEntityProvider implements EntityProviderInterface
{
    public function get(?StoreInterface $store = null, ?array $entityIds = []): ?\Generator
    {
        $customEntityCollection = $this->getCollection(store: $store, entityIds: $entityIds);
        foreach ($customEntityCollection as $customEntity) {
            yield $customEntity;
        }
    }
    
    private function getCollection(?StoreInterface $store, ?array $entityIds): CategoryCollection
    {
        $customEntityCollection = $this->customEntityCollectionFactory->create();
        if ($store) {
            $customEntityCollection->setStore(store: (int)$store->getId());
        }
        if ($entityIds) {
            $customEntityCollection->addFieldToFilter(
                Entity::DEFAULT_ENTITY_ID_FIELD,
                ['in' => implode(',', $entityIds)],
            );
        }

        return $customEntityCollection;
    }
}

```


[title] Version Comparison
[path] Klevu Module v4.x Overview/

## Improvements

- PHPUnit Integration tests with code coverage \~80%.
- PHPCS to a stricter standard than Magento.
- PHPStan to Level 6 (Level 9 for non-Magento modules, e.g. PHP-SDK)
- Separation of concerns, each module can be removed if not required.

### Frontend

- Setting of Theme JS settings via the admin.
- Single URL for search results.
- Addition of recommendations banner widget.
- Correct filtering of visibility without any customisation.
- Correct currency conversion including symbols defined in Magento.
- Move Javascript to page end where possible.&#x20;
- Add Javascript to the head in a non-blocking manner where possible.
- Remove all Klevu code from the checkout

### Indexing (Data Sync)

- Switch to Klevu JSON indexing from XML indexing.
- Removal of on-the-fly calculation of indexing actions.
- Customer group pricing includes catalog price rules.
- Use Magento image generation for Klevu images.

***

|                                                             | **v2.x/v3.x**                                                                                                                                                                        | **v4.x**                                                                                                                                                                                                                                 |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Plugin                                                      | Migrated from Magento 1.                                                                                                                                                             | Purpose-built for Magento 2 following Magento’s best practice.                                                                                                                                                                           |
| PHP support                                                 | 5.6+&#xA;Limits PHP features that can be used, e.g. type hints.&#xA;Versions of PHP that are EOL contain security bugs.                                                              | 8.1+&#xA;Make full use of newer PHP features (type hints, named args, null safe op, etc..)&#xA;Performance improvements from newer versions of PHP.                                                                                      |
| Magento Support                                             | 2.1.18 - 2.4.6<br />Includes workarounds for missing features, core bugs, etc..&#xA;Support for the old version means v2.x of the extension cannot be listed on Magento Marketplace. | 2.4.4+<br />Only supports Magento versions supported by Adobe.                                                                                                                                                                           |
| Future Klevu Development                                    | Will receive feature updates until v4.x General Availability and security updates for 1 year after the launch.                                                                       | Will receive all new features, including message queues for indexing and analytics, partial product data sync and multi-store integration with one API key.                                                                              |
| Klevu API                                                   | XML API                                                                                                                                                                              | JSON API                                                                                                                                                                                                                                 |
| Test Code Coverage                                          | \~14%                                                                                                                                                                                | \~80%                                                                                                                                                                                                                                    |
| PHPCS compliant                                             | No                                                                                                                                                                                   | Yes, to a stricter standard than Magento’s PHPCS.                                                                                                                                                                                        |
| PHPStan compliant                                           | No                                                                                                                                                                                   | Yes, to level 6 for the Magento modules (level 9 for PHP-SDK and PHP-pipelines)                                                                                                                                                          |
| Separation of concerns                                      | Indexing and search code mixed in the same module.                                                                                                                                   | A module for each feature. Indexing, frontend and analytics are separated. &#xA;Each indexing entity type and frontend solution is added via separate modules.&#xA;Designed to have non-required modules removed via `composer replace`. |
| Object Manager                                              | Is used in the code and can not be removed due to circular dependencies.                                                                                                             | No usage outside of Magento's best practice guidelines (e.g. constructor arguments, factories or tests).                                                                                                                                 |
| Can code be modified via plugins?                           | Not all due to some variables passed by reference.                                                                                                                                   | Yes, this is the recommended way of modifying all Klevu code.                                                                                                                                                                            |
| Klevu JS Theme customisations                               | Via a custom module only.                                                                                                                                                            | Via admin settings, themes or a custom modules.                                                                                                                                                                                          |
| Search Results URL                                          | Custom URL `/search` can not be changed.&#xA;Magento results URL is also available at `/catalogsearch/result` causing duplicate content.                                             | Reuses the Magento search URL `/catalogsearch/result` can be changed as required. &#xA;Toggle between Klevu Theme JS results and Magento via a URL parameter.                                                                            |
| Recommendations Banners                                     | Code has to be added manually. Code provided via KMC does not work with dynamic blocks.                                                                                              | Added via a widget with an option to make it compatible with dynamic blocks. Only the recs banner ID is required.                                                                                                                        |
| Custom Product Types                                        | Possible, but not simple to implement. Requires preferencing classes which could lead to breaking the upgrade path for the module.                                                   | Built with custom product types in mind. Inject an `entityProvider` class for the custom type via `di.xml`                                                                                                                               |
| Custom Entity Types                                         | Possible, but not simple to implement. Requires preferencing classes and breaking the upgrade path for the module.                                                                   | Built with custom entity types in mind. Inject an `entityIndexerService` class for the new type via `di.xml`                                                                                                                             |
| Entity data sent to Klevu during indexing.                  | Syncs many attributes which may not be required by your store.                                                                                                                       | Sync only the data required for your store.                                                                                                                                                                                              |
| Customisation of entity data sent to Klevu during indexing. | Requires preferencing a class and breaking the upgrade path for the module.&#xA;&#xA;                                                                                                | Uses Klevu YAML pipelines which can be overridden by injecting your own YAML file via `di.xml`. Option to auto-generate YAML for custom attributes. No code is required to add data to indexing.                                         |
| Indexing next action calculation                            | During indexing the action to perform is calculated on the fly. This can be extremely resource-heavy and time-consuming for larger stores.                                           | The next action is calculated in advance of the sync and stored in the database tables. Sync then reads those tables and performs the required action.                                                                                   |
| Klevu script tags                                           | Multiple script tags are added that should have been combined into one.                                                                                                              | Reduction in the number of tags added.                                                                                                                                                                                                   |
| Klevu interactive                                           | Is in use. Klevu JS waits until page is interactive before firing.                                                                                                                   | Removed. Klevu JS executes immediately. Any Klevu JS that has other dependencies is handled via webhooks and is executed when available.                                                                                                 |
| Headless Frontend                                           | Frontend modules have to remain installed, enabled and enabled in the config.                                                                                                        | All fronted modules can be removed via `composer replace` if a headless implementation is required.                                                                                                                                      |
|                                                             |                                                                                                                                                                                      |                                                                                                                                                                                                                                          |


[title] Roadmap
[path] Klevu Module v4.x Overview/

These features are planned for future releases.

### Automated Migration of Account

Automatically migrate Klevu XML Indexing accounts to use Klevu JSON Indexing. Currently this is a manual process and could result in Klevu frontend solutions being disabled after migrating to v4.x. See the [recommended production release documentation](https://docs.klevu.com/klevu-magento-v4/recommended-production-migration-process) to avoid this situation.

### Preserve Layout

This is not currently supported in v4.x. **Please do not migrate if you are using Preserve Layout.**

### Partial Data Sync

The plugin handles delta sync out of the box, i.e. only sync entities that have changed. We will also be adding [partial data sync](https://docs.klevu.com/indexing-apis/partial-updates-patch) in a future release, e.g. if only the price has changed, only send the price data.

### Account Integration at Website Scope

Integrate multiple Magento store views with the same Auth Keys. Using channels and locales to process the data from multiple stores.

### Queues

Add support for Rabbit MQ to process activities currently handled via cron. With priority queues for updates of price and stock data.

### Indexing Certain Standard Attributes

The following attributes are not indexed to Klevu out of the box. You are free to implement this yourself if it is urgent.

- `image.hover`&#x20;
- `swatchInfo`


[title] Installation & Integration
[path] /


[title] Queue Orders For Sync
[path] Analytics/

:::hint{type="warning"}
Order queueing is only performed on stores which have been integrated with Klevu.
Additionally, stores which have the setting **Klevu** > **Data Sync** > **Order Analytics** > **Order Sync Status** set to Disable will not queue orders.
:::

## Automatically on Order Submit

The module listens to the `sales_model_service_quote_submit_success` event triggered by Magento when a quote / cart is converted to an order and persisted successfully. A record is created in the `klevu_sync_order` database table, in a `queued` status.

## Manually via Command Line

You can manually add or re-queue orders via the terminal using the `klevu:analytics:queue-orders-for-sync` command. Orders can be specified using a combination of order id; current sync status; and store id, supporting a variety of scenarios, including

- Manually queueing (or re-queueing) individual records
- Re-queueing failed orders
- Backfilling orders for a newly integrated store

The command line also supports ignoring the **Klevu** > **Data Sync** > **Order Analytics** > **Order Sync Status** configuration value, if desired.

Records are created in the `klevu_sync_order` database table in a queued state for orders which have never previously been queued. Where a record already exists in the database, and is *not* in a queued or retry status, its status will be updated to `retry`.

[title] Search Theme Layout
[path] Frontend/Theme JS/

## Overview

If you have customised Search Theme Layout in KMC you will have JS and CSS files to add to your Magento installation.&#x20;

There are multiple ways to achieve this, via a theme or a module.

- Add via your theme if the changes are only required on that theme or base theme.
- Add via a module if the changes are required on all themes or if there is some extra business logic required in a ViewModel to determine when the templates should be used.
- It is also possible to combine the approaches if changes are required in one (base) theme, but also require business logic from a ViewModel.

For these examples, we will refer to those files as `klevu-theme-starter.js` and `klevu-theme-starter.css`. Your actual filenames will differ from these.

## Add via Theme

[Magento theme structure docs.](https://developer.adobe.com/commerce/frontend-core/guide/themes/structure/)

In this example, we are using `Vendor/theme` as your theme.

Create a directory in your theme for `Klevu_Frontend` within this directory add the  structure as below:

```none
app
- design
 - frontend
  - Vendor
   - theme
    - Klevu_Frontend
     - layout
     - templates
     - web
      - css
      - js
```

Add the CSS file to `web/css` directory
Add the Javascript file to `web/js` directory

Create a layout file to inject the template into your theme via the container `Klevu_Frontend.before.body.end`. This container enables us to easily remove all Klevu scripts from a page, e.g. checkout.

:::CodeblockTabs
app/design/frontend/Vendor/theme/Klevu\_Frontend/layout/default.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <!-- This container contains all Klevu scripts added before body end -->
        <referenceContainer name="Klevu_Frontend.before.body.end">
            <block name="Vendor_Theme.jsv2_theme"
                   template="Klevu_Frontend::jsv2_theme.phtml"
                   before="-"/>
        </referenceContainer>
    </body>
</page>
```
:::

&#x20;Create the template file which contains the CSS and Javascript links

:::CodeblockTabs
app/design/frontend/Vendor/theme/Klevu\_Frontend/templates/jsv2\_theme.phtml

```php
<?php

declare(strict_types=1);

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Helper\SecureHtmlRenderer;

/**
 * @var Template $block
 * @var SecureHtmlRenderer $secureRenderer
 */
?>
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: [
        'type' => 'text/javascript',
        'src' => $block->getViewFileUrl('Klevu_Frontend::js/klevu-theme-starter.js')
    ],
) ?>
<?= $secureRenderer->renderTag(
    tagName: 'link',
    attributes: [
        'rel' => 'stylesheet',
        'href' => $block->getViewFileUrl('Klevu_Frontend::css/klevu-theme-starter.css')
    ],
) ?>

```
:::

## Add via Module

[Magento module creation documentation](https://experienceleague.adobe.com/en/docs/commerce-learn/tutorials/backend-development/create-module).

In this example, we are using `Vendor/Module` as your module.

Create the module and add the following structure to view. Note: full module creation is not shown here.

```none
app
- code
 - Vendor
  - Module
   - view
    - frontend
     - layout
     - templates
     - web
      - css
      - js
```

Add the CSS file to `web/css` directory
Add the Javascript file to `web/js` directory

Create a layout file to inject the template into your theme via the container `Klevu_Frontend.before.body.end`. This container enables us to easily remove all Klevu scripts from a page, e.g. checkout.

:::CodeblockTabs
Vendor/Module/view/frontend/layout/default.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <!-- This container contains all Klevu scripts added before body end -->
        <referenceContainer name="Klevu_Frontend.before.body.end">
            <block name="Vendor_Module.jsv2_theme"
                   template="Vendor_Module::jsv2_theme.phtml"
                   before="-"/>
        </referenceContainer>
    </body>
</page>
```
:::

Create the template file which contains the CSS and Javascript links

:::CodeblockTabs
Vendor/Module/view/templates/jsv2\_theme.phtml

```php
<?php

declare(strict_types=1);

use Magento\Framework\View\Element\Template;

/**
 * @var Template $block
 */
?>
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: [
        'type' => 'text/javascript',
        'src' => $block->getViewFileUrl('Vendor_Module::js/klevu-theme-starter.js')
    ],
) ?>
<?= $secureRenderer->renderTag(
    tagName: 'link',
    attributes: [
        'rel' => 'stylesheet',
        'href' => $block->getViewFileUrl('Vendor_Module::css/klevu-theme-starter.css')
    ],
) ?>

```
:::


[title] Toggle View
[path] Frontend/Theme JS/

For both the Search Results Landing Page (SRLP) and Category Navigation, the theme can be toggled between JS Theme and Magento native with the addition of a URL parameter.

### Preview Theme JS

When Using Magento native theme for SRLP or Category Navigation add `?klevu_layout_preview=klevu` to the URL to preview Klevu Theme JS.

### Preview Native Magento&#x20;

When Using Klevu JS Theme for SRLP or Category Navigation add `?klevu_layout_preview=magento` to the URL to preview the results using the native Magento theme.

[title] Excluding CMS Pages
[path] Indexing/Entities/CMS Pages/

You may wish to exclude certain CMS pages from the sync.&#x20;

To do this we inject an `isIndexableCondition` into the `isIndexableConditions` array for the virtual type `Klevu\IndexingCms\Service\Determiner\IsIndexableDeterminer`

:::CodeblockTabs
XML

```xml
<virtualType name="Klevu\IndexingCms\Service\Determiner\IsIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="pageIsIndexableCondition"
                  xsi:type="object">Vendor\Module\Service\Determiner\ExcludedPagesIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create that class, which must implement the `IsIndexableConditionInterface`&#x20;

:::CodeblockTabs
Vendor\Module\Service\Determiner\ExcludedPagesIsIndexableCondition.php

```php
<?php

namespace Vendor\Module\Service\Determiner;

use Klevu\IndexingApi\Service\Determiner\IsIndexableConditionInterface;
use Magento\Cms\Api\Data\PageInterface;

class ExcludedPagesIsIndexableConditionr implements IsIndexableConditionInterface
{
    /**
     * Edit routes as required
     * Alternatively inject these via di.xml
     *
     * @param string[]
     */
    private array $excludedPages = [
        'no-route',
        'service-unavailable',
    ];
    
    public function execute(
        ExtensibleDataInterface|PageInterface $entity,
        StoreInterface $store,
    ): bool {
        if (!($entity instanceof PageInterface)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Invalid argument provided for "$entity". Expected %s, received %s.',
                    PageInterface::class,
                    get_debug_type($entity),
                ),
            );
        }
        
        return !in_array(
            needle: $page->getIdentifier(), 
            haystack: $this->excludedPages, 
            strict: true,
        );
    }
}

```
:::

See [Entities Is Indexable Determiner](https://docs.klevu.com/klevu-magento-v4/entities-is-indexable-determiner) for more information.

[title] Registering Attributes that are not Magento Attributes
[path] Indexing/Attributes/Discovery/

There may be cases where you need to index some entity data to Klevu where a Magento attribute does not represent that data.

:::hint{type="info"}
If the data needs to be searchable and/or filterable then creating a static attribute is the recommended way to handle that. However, if the data is only to be used on the frontend, then sending it in `additionalDataToReturn` is a simpler approach and a static attribute would not be required.
:::

e.g. For a product you want to send the following data in the entity payload

```json
{
    "name": "Product Name",
    "sku": "SKU-101",
    "some_attribute": "This is not a Magento attribute, but some third-party data"
}
```

Where `some_attribute` is not a Magento attribute but is data pulled from some third-party source.
With the Klevu JSON API, we **must** register `some_attribute` as an attribute before sending data for that attribute in the entity payload.

Klevu provides `StaticAttributeProvider` to accomplish this. Called “static” as they are hardcoded in the `di.xml` and cannot be updated via the admin or the database.

We add attributes to `StaticAttributeProvider` by injecting the required attribute(s) into the attributes argument via `di.xml`. &#x20;
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\IndexingProducts\Service\Provider\StaticAttributeProvider">
    <arguments>
        <argument name="attributes" xsi:type="array">
            <item name="some_attribute" xsi:type="array">
                <item name="attribute_id" xsi:type="number">100001</item> <!-- required -->
                <item name="attribute_code" xsi:type="string">some_attribute</item> <!-- required -->
                <item name="is_searchable" xsi:type="boolean">true</item> <!-- optional: default = false -->
                <item name="is_filterable" xsi:type="boolean">false</item> <!-- optional: default = false -->
                <item name="is_returnable" xsi:type="boolean">true</item> <!-- optional: default = false -->
                <item name="default_label" xsi:type="string">Some Attribute</item> <!-- optional: default = attribute_code with underscores removed and uppercase first letter -->
                <item name="labels" xsi:type="array"> <!-- optional: item names are store ids -->
                    <item name="1" xsi:type="string">Store Label</item>
                    <item name="2" xsi:type="string">Étiquette du magasin</item>
                    <item name="3" xsi:type="string">Store-Etikett</item>
                </item>
                <!-- The following are used to determine what attribute type is created in Klevu -->
                <!-- Klevu attribute types are STRING, NUMBER, MULTIVALUE -->
                <!-- If none of these are set the default attribute type is STRING -->
                <item name="frontend_input" xsi:type="string">select</item> <!-- optional -->
                <item name="backend_type" xsi:type="string">int</item> <!-- optional -->
                <item name="source_model" xsi:type="string">Vendor\Module\Model\Source\SomeAttributeSource</item> <!-- optional -->
                <item name="is_html_allowed_on_front" xsi:type="number">1</item> <!-- optional -->
                <item name="is_global" xsi:type="number">1</item> <!-- optional -->
            </item>
        </argument>
    </arguments>
</type>
```
:::

We can do the same for Categories injecting into `Klevu\IndexingCategories\Service\Provider\StaticAttributeProvider`

 

[title] Attributes
[path] Indexing/

## JSON API

Klevu Magento v4 uses the [Klevu Data Indexing JSON API](https://docs.klevu.com/indexing-apis) which requires the registering of any custom attributes before entity data can be sent to Klevu for those attributes.&#x20;

## Standard vs Custom Attributes

Klevu has a set of standard attributes that already exist for your account. At the time of writing those attributes are:

```none
'additionalDataToReturn'
'category'
'currency'
'description'
'id'
'image'
'imageHover'
'inStock'
'itemGroupId'
'listCategory'
'name'
'price'
'rating'
'ratingCount'
'salePrice'
'shortDescription'
'sku'
'startPrice'
'swatchInfo'
'tags'
'toPrice'
'url'
'visibility'
```

These standard attributes are immutable and therefore their settings can not be changed.
It is also possible for merchants to register custom attributes with Klevu. This registration is handled via the `Register with Klevu` setting on the attribute.

## Database

Upon installation, the Klevu module will create a database table `klevu_indexing_attribute` to maintain the status of all attributes. This database is automatically populated via attribute discovery after account integration.&#x20;

This database table is updated whenever relevant attribute data is changed. e.g. a name change or an attribute is made searchable. These changes will update the `next_action` column. The `next_action` will be set to either  , `Add`, `Delete` or `Update`. This ---column defines what action will take place during the next sync.

***

## Admin Attribute Settings

When editing any attribute in the admin you will find a new section Klevu Indexing at the bottom of the Properties tab. This new section has 2 options:



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/aco8WgAoF1XKEO1CJCBCh_screenshot-2024-09-12-at-154601.png "Magento Attribute Properties")

### Register with Klevu

This setting determines whether an attribute is registered with Klevu or not. Changing this setting will not send the request to Klevu immediately. The attribute record in the database table `klevu_indexing_attributes` will have the `next_action` column updated to `Add`, `Update` or `Delete` depending on the value of this setting.&#x20;
When the cronjob next runs it will pick up all entries in this table with a `next_action` and send those API requests.

:::hint{type="warning"}
If a product attribute is set to `Register with Klevu` it does not automatically meant that an update will be sent for an entity if that attribute value is updated, unless `Triggers Update of` is also set.
:::

### Automatically Generate Pipeline Configuration For

For which product types should this data be automatically added to the data sent in entity sync? e.g for `color` or `size` we would probably want to sync that data for `simple` and `configurable (variants)` but not `virtual`, `downloadable` or `configurable (parents)`.
This setting is dependent on `Register with Klevu` being set to `Yes` and otherwise it will be hidden.&#x20;

:::hint{type="warning"}
If a product attribute is set to `Register with Klevu` it does not automatically meant that the data for that attribute is automatically sent to Klevu when entity sync is run, unless `Automatically Generate Pipeline Configuration For` is set for that product type.

Those generated pipeline files can be found in `var/klevu/indexing/pipeline/`
:::

### Triggers Update of

When saving an entity (category, CMS page, product or custom type) we do not always trigger an update in Klevu.&#x20;
e.g. if the only data on the product that has changed is the `weight` and we’re not sending `weight` in the product sync, then we don’t need to send an update for that product.

However, there will be attributes we do not sync that we want to trigger a sync when changed.&#x20;
e.g. when `tax_class_id` of a product is changed we would want to trigger an update of the price. This setting determines what data to send when the attribute data is updated on the entity.

:::hint{type="info"}
Currently selecting any option other than `Nothing` will sync the full product data. Partial product data sync is on the roadmap for a future release.
:::

### Custom Attributes Behaviour

All attributes in Klevu have the following settings

- Searchable - should this value be used in search
- Filterable - should this attribute be usable as a facet
- Returnable - should this attribute data be returned to the frontend

For any custom attribute, these values are controlled by the following attribute config settings:

- Searchable - `Use in Search`
- Filterable - `Use in Layered Navigation`
- Returnable - `Used in Product Listing`

:::hint{type="info"}
Note: Standard Klevu attributes (listed above) have predefined settings for these values and are immutable. They will not use these setting from Magento admin.
:::

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/mn-kAzH7Itmf2jHXCAIiu_screenshot-2024-03-25-at-221100-1.png "Magento Attribute Storefront Properties")


[title] Custom Entity Types
[path] Indexing/Entities/

## Entity Discovery

In order to sync any entities first we have to discover them. In order to discover entites for a new entity type we must inject an `EntityDiscoveryProvider` into the `EntityDiscoveryOrchestratorService`&#x20;
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Indexing\Service\EntityDiscoveryOrchestratorService">
    <arguments>
        <argument name="discoveryProviders" xsi:type="array">
            <item name="custom_types"
                  xsi:type="object">Vendor\Module\Service\Provider\EntityDiscoveryProvider</item>
        </argument>
    </arguments>
</type>

```
:::

That `CustomTypeEntityDiscoveryProvider` will be a virtual type of `Klevu\Indexing\Service\Provider\EntityDiscoveryProvider`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\EntityDiscoveryProvider"
             type="Klevu\Indexing\Service\Provider\EntityDiscoveryProvider">
    <arguments>
        <argument name="entityType" xsi:type="string">CUSTOM_TYPE</argument>
        <argument name="entityProviders" xsi:type="array">
            <item name="custom_type"
                  xsi:type="object">Vendor\Module\Service\Provider\CustomTypeEntityProvider</item>
        </argument>
        <argument name="isIndexableDeterminer"
                  xsi:type="object">Vendor\Module\Service\Determiner\IsIndexableDeterminer</argument>
    </arguments>
</virtualType>

```
:::

Create the `CustomTypeEntityProvider` which must implement `Klevu\IndexingApi\Service\Provider\EntityProviderInterface`

```php
class CustomTypeEntityProvider implements EntityProviderInterface
{
    public function get(?StoreInterface $store = null, ?array $entityIds = []): ?\Generator
    {
        $customEntityCollection = $this->getCollection(store: $store, entityIds: $entityIds);
        foreach ($customEntityCollection as $customEntity) {
            yield $customEntity;
        }
    }
    
    private function getCollection(?StoreInterface $store, ?array $entityIds): CategoryCollection
    {
        $customEntityCollection = $this->customEntityCollectionFactory->create();
        if ($store) {
            $customEntityCollection->setStore(store: (int)$store->getId());
        }
        if ($entityIds) {
            $customEntityCollection->addFieldToFilter(
                Entity::DEFAULT_ENTITY_ID_FIELD,
                ['in' => implode(',', $entityIds)],
            );
        }

        return $customEntityCollection;
    }
}

```

***

## Entity Sync

After discovering the entities, we need to sync them with Klevu by injecting `EntityIndexerService` services into the `EntitySyncOrchestratorService`. We inject a separate service for each action, i.e. `Add`, `Delete` and `Update`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Indexing\Service\EntitySyncOrchestratorService">
    <arguments>
        <argument name="entityIndexerServices" xsi:type="array">
            <item name="CUSTOM_TYPE" xsi:type="array">
                <item name="add"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Add</item>
                <item name="delete"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Delete</item>
                <item name="update"
                      xsi:type="object">Vendor\Module\Service\EntityIndexerService\Update</item>
            </item>
        </argument>
    </arguments>
</type>

```
:::

Now create each of the injected `EntityIndexerService`.

:::hint{type="info"}
You can create your own service classes that implement `\Klevu\IndexingApi\Service\EntityIndexerServiceInterface` and handle indexing the data with Klevu. If you choose this route please refer to the Klevu PHP-SDK documentation.

If you wish to use Klevu pipelines to index data with Klevu please continue following the example below.
:::

Create a virtual type of `Klevu\Indexing\Service\EntityIndexerService`.&#x20;
Repeat this step for `Delete` and `Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\EntityIndexerService\Add"
             type="Klevu\Indexing\Service\EntityIndexerService">
    <arguments>
        <argument name="entityIndexingRecordProvider"
                  xsi:type="object">Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider\Add</argument>
        <argument name="pipelineConfigurationFilepath"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update.yml</argument>
    </arguments>
</virtualType>
<!-- Repeat for Delete and Update -->
```
:::

Create a virtualType of `Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider` (which doesn't exist yet) to set the action to be performed.&#x20;
Repeat this step for `Delete` and `Update` actions

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider\Add"
             type="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider">
    <arguments>
        <argument name="action" xsi:type="string">Add</argument>
    </arguments>
</virtualType>
<!-- Repeat for Delete and Update -->
 
```
:::

Now create the missing `Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider` mentioned in the previous step. This is a virtual type of `Klevu\Indexing\Service\Provider\Sync\EntityIndexingRecordProvider`.
Pass in the same `entityProvider` we created during the Entity Discover section above.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\Sync\EntityIndexingRecordProvider"
             type="Klevu\Indexing\Service\Provider\Sync\EntityIndexingRecordProvider">
    <arguments>
        <argument name="entityProviders" xsi:type="array">
            <!-- ALREADY CREATED IN DISCOVERY SECTION ABOVE -->
            <item name="custom_type"
                  xsi:type="object">Vendor\Module\Service\Provider\CustomTypeEntityProvider</item>
        </argument>
        <argument name="indexingRecordCreatorService"
                  xsi:type="object">Vendor\Module\Service\EntityIndexingRecordCreatorService</argument>
        <argument name="entityType" xsi:type="string">CUSTOM_TYPE</argument>
    </arguments>
</virtualType>
```
:::

Create `Vendor\Module\Service\EntityIndexingRecordCreatorService` which implements `Klevu\IndexingApi\Service\EntityIndexingRecordCreatorServiceInterface`

:::CodeblockTabs
php

```php
class EntityIndexingRecordCreatorService implements EntityIndexingRecordCreatorServiceInterface
{
    public function execute(
        int $recordId,
        Actions $action,
        PageInterface|ExtensibleDataInterface $entity,
        PageInterface|ExtensibleDataInterface|null $parent = null,
    ): EntityIndexingRecordInterface {
    
       return $this->entityIndexingRecordFactory->create([
            'recordId' => $recordId,
            'entity' => $entity,
            'parent' => $parent, // this is used when indexing configurable variants. If the entity has no parent set this to null.
            'action' => $action,
        ]);
    }
}

```
:::

Final step is to create the pipeline YAML file to process that data before it is sent to Klevu.
`Vendor_Module::etc/pipeline/add_update.yml`. See [Pipelines](https://app.archbee.com/public/PREVIEW-8cIJaE_9UAmWKNnQcRcUb/PREVIEW-1ftUqiDYJF1lFcslr73EX).


[title] Update
[path] Indexing/Attributes/Discovery/

:::hint{type="warning"}
Attribute update does not send any data to Klevu.

Its only purpose is to update the attributes in `klevu_indexing_attribute` database table and calculate their `next_action`
:::

Attribute Update triggers Attribute Discovery for a selection of entity IDs.
Various plugins and observers trigger an attribute update, e.g. when an attribute is saved.

Attribute update will:

- add any missing attributes and determine if those [attributes are indexable](https://docs.klevu.com/klevu-magento-v4/attribute-is-indexable-determiner).
- set any of the passed attribute IDs which are no longer indexable, but were previously registered, to have a `next_action` of `Delete`.
- set any of the passed attribute IDs that have become indexable to have a `next_action` of `Add`.
- set the `next_action` for the passed attribute IDs to `Update` if they are indexable.

Attribute update will **NOT**:

- send any data to Klevu.

Attribute update is triggered:

- via plugins
- via observers
- via CLI

`\Klevu\Indexing\Service\AttributeUpdateOrchestratorService` responsible for attribute update. All the above methods of triggering attribute update use this service.

### CLI

`klevu:indexing:attribute-update`

The update can also be triggered via CLI and has 1 required parameter and 2 optional parameters&#x20;

- `attribute-ids` - comma-separated list of attribute IDs to update
- `api-keys` - \[optional] comma-separated list of API keys to update
- `attribute-types` - \[optional] comma-separated list of  attribute types to update, options:
  - `KLEVU_PRODUCT`&#x20;
  - `KLEVU_CATEGORY`

e.g

```shell
bin/magento klevu:indexing:attribute-update \
    --attribute-ids="1,2,3" \
    --attribute-types="KLEVU_PRODUCT" \
    --api-keys="klevu-example-js-api-key" 

```


[title] Removing Klevu Modules
[path] Installation & Integration/

### Step 1 - Remove v4.x packages

Remove the modules via composer.&#x20;

```shell
composer remove "klevu/*"
```


[title] Result Landing Page (SRLP) URL
[path] Frontend/Search/

## Change Default SRLP URL

The Search Result Landing Page (SRLP) URL in Magento (without any changes) is `/catalogsearch/result`.

In v2.x/v3.x version of the Klevu module an extra SRLP route was added with a URL of `/search`.&#x20;
Having 2 routes is not ideal. In v4.x there is only one search route and by default, that route is the same as the Magento default, i.e. `/catalogsearch/result`.&#x20;

In v2.x/v3.x it was possible to switch between the 2 SRLP URLs to compare the search results from Klevu and native Magento. This can still be done by adding `?klevu_layout_preview=klevu` or `?klevu_layout_preview=native` to the SRLP URL.

Note all examples below use Module `Vendor_Module`.
Update to match your module. [How to create a module.](https://experienceleague.adobe.com/docs/commerce-learn/tutorials/backend-development/create-module.html?lang=en)

### 1. Create the Route

Create a new route so Magento directs the request to your module.

:::CodeblockTabs
Vendor/Module/etc/frontend/routes.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="catalogsearch" frontName="your-search-url">
            <module name="Vendor_Module" before="Klevu_FrontendSearch"/>
        </route>
    </router>
</config>

```
:::

- The route `id` MUST be `catalogsearch`.
- The route `frontName` is your new search URL, replace your-search-url with your desired URL.
- `<module` MUST set `before="Klevu_FrontendSearch"` to replace config in the module Klevu\_FrontendSearch. Also ensure your `module.xml` has a dependency on `Klevu_FrontendSearch`.

### 2. Define the Controller Name

Pass the controller name to the LandingUrlProvider. This handles the second part of the request url. Without this, the Klevu plugin will not provide the correct SRLP URL to Klevu when triggering the search.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Klevu\FrontendSearch\Service\Provider\LandingUrlProvider">
        <arguments>
            <argument name="controllerName" xsi:type="string">controller-name-change-me</argument>
        </arguments>
    </type>
</config>
```
:::

- `controllerName` is the directory containing the Action i.e. `$this->request->getControllerName()`.
- By Default `controllerName` is `result`. This directs requests to the controller `Controller/Result/Index.php` i.e. `your.site/catalogsearch/result`.
- If using `Index` as the `controllerName` you can pass `/` as the `controllerName` argument. e.g. `Controller/Index/Index.php` i.e. `your.site/search`.

### 3. Inject Conditions To Check if Enabled

If no conditions are provided then the is enabled check will return true.

:::CodeblockTabs
vendor/Module/etc/di.xml

```xml
<type name="Klevu\FrontendSearch\Controller\Result\Index">
    <arguments>
        <argument name="logger" xsi:type="object">Klevu\Indexing\Logger\Logger</argument>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_integrated"
                  xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
            <item name="klevu_modules_enabled" xsi:type="array">
                <item name="klevu_srlp_enabled"
                      xsi:type="object">Klevu\FrontendSearch\Service\IsEnabledCondition\IsSrlpEnabledCondition</item>
            </item>
        </argument>
    </arguments>
</type>
```
:::

### 4. Create A Controller To Handle The Request

:::CodeblockTabs
Vendor/Module/Controller/ControllerNameChangeMe/Index.php

```php
<?php

declare(strict_types=1);

namespace Vendor\Module\Controller\ControllerNameChangeMe;

use Klevu\Frontend\Exception\InvalidIsEnabledDeterminerException;
use Klevu\Frontend\Exception\OutputDisabledException;
use Klevu\FrontendApi\Service\IsEnabledDeterminerInterface;
use Klevu\FrontendSearch\Service\Provider\QueryTextProviderInterface;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Session;
use Magento\CatalogSearch\Controller\Result\Index as CatalogSearchResultIndex;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\State as AppState;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\LocalizedException;
use Magento\Search\Model\QueryFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

class Index extends CatalogSearchResultIndex 
    implements HttpGetActionInterface, HttpPostActionInterface
{
    /**
     * @var QueryTextProviderInterface
     */
    private QueryTextProviderInterface $queryTextProvider;

    public function __construct(
        Context $context,
        Session $catalogSession,
        StoreManagerInterface $storeManager,
        QueryFactory $queryFactory,
        Resolver $layerResolver,
        QueryTextProviderInterface $queryTextProvider,
        Escaper $escaper,
        LoggerInterface $logger,
        AppState $appState,
        IsEnabledDeterminerInterface $isEnabledDeterminer,
        array $isEnabledConditions = [],
    ) {
        parent::__construct(
            context: $context,
            catalogSession: $catalogSession,
            storeManager: $storeManager,
            queryFactory: $queryFactory,
            layerResolver: $layerResolver,
        );

        $this->queryTextProvider = $queryTextProvider;
        $this->escaper = $escaper;
        $this->logger = $logger;
        $this->appState = $appState;
        $this->isEnabledDeterminer = $isEnabledDeterminer;
        $this->isEnabledConditions = $isEnabledConditions;
    }

    /**
     * @return void
     */
    public function execute()
    {
        if (!$this->isKlevuEnabled()) {
            parent::execute();

            return;
        }
        $this->setPageTitle();
        $this->_view->renderLayout();
    }

    /**
     * @return void
     */
    private function setPageTitle(): void
    {
        $query = $this->queryTextProvider->get();
        $this->_view->loadLayout();
        $page = $this->_view->getPage();
        $config = $page->getConfig();
        $title = $config->getTitle();
        $title->set(
            __("Search results for: '%1'", $query)->render(),
        );
    }
    
    /**
     * @return bool
     * @throws InvalidIsEnabledDeterminerException
     */
    private function isKlevuEnabled(): bool
    {
        $return = false;
        try {
            $this->isEnabledDeterminer->executeAnd($this->isEnabledConditions);
            $return = true;
        } catch (InvalidIsEnabledDeterminerException $exception) {
            if ($this->appState->getMode() !== AppState::MODE_PRODUCTION) {
                throw $exception;
            }
            $this->logger->error(
                message: 'Method: {method}, Error: {error}',
                context: [
                    'method' => __METHOD__,
                    'error' => $exception->getMessage(),
                ],
            );
        } catch (OutputDisabledException) {
            // Output is disabled.
        }

        return $return;
    }
}

```
:::

- Change `ControllerNameChangeMe` in the Controller path and namespace to match that set in `LandingUrlProvider` `controllerName` argument in `etc/di.xml` (see previous step).


[title] Is Indexable Determiner
[path] Indexing/Attributes/Discovery/

## Determiners & Conditions

If an attribute is indexable is determined by `Klevu\Indexing\Service\Determiner\IsAttributeIndexableDeterminer`
This determiner loops through all injected `Klevu\IndexingApi\Service\Determiner\IsAttributeIndexableConditionInterface` classes.
If **any** of these return false; then the attribute is set to **not indexable** and will not be registered with Klevu.&#x20;
If they **all** return true; then the attribute is indexable and can be registered with Klevu.

By default, the only setting checked to determine if an attribute is indexable is the new **Register with Klevu&#x20;**&#x73;etting on the attribute.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/caUOqUccmlgPIwZfFr651_screenshot-2024-08-06-at-151355.png "Klevu Attribute Settings")

Both `module-ms-indexing-categories` and `module-m2-indexing-products` create virtual types of this class and inject an array of conditions.
e.g.

:::CodeblockTabs
module-m2-indexing-products/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Determiner\IsAttributeIndexableDeterminer"
             type="Klevu\Indexing\Service\Determiner\IsAttributeIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="indexTypeIsIndexableCondition"
                  xsi:type="object">Klevu\IndexingProducts\Service\Determiner\AttributeIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>
```
:::

***

## Custom Conditions

You can add conditions to amend the default behaviour.
Let's say you only wanted to register attributes when the attribute code began with `vendor_`.
You’d inject your condition in to the `IsAttributeIndexableDeterminer` via the `isIndexableConditions` array in your `di.xml`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Determiner\IsAttributeIndexableDeterminer">
    <arguments>
        <argument name="isIndexableConditions" xsi:type="array">
            <item name="indexTypeIsIndexableCondition"
                  xsi:type="object">Vendor\Module\Service\Determiner\AttributeCodeBeginsWithIsIndexableCondition</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create that class implementing the interface `Klevu\IndexingApi\Service\Determiner\IsAttributeIndexableConditionInterface`

:::CodeblockTabs
Vendor/Module/Service/Determiner/AttributeCodeBeginsWithIsIndexableCondition.php

```php
<?php

namespace Vendor\Module\Service\Determiner;

use Klevu\IndexingApi\Service\Determiner\IsAttributeIndexableConditionInterface;

class AttributeCodeBeginsWithIsIndexableCondition implements IsAttributeIndexableConditionInterface
{
    public function execute(
        AttributeInterface $attribute, 
        StoreInterface $store
    ): bool {
        return str_starts_with(
            haystck: $attribute->getCode(), 
            needle: 'vendor_',
        );
    }
}
```
:::

See `Klevu\IndexingProducts\Service\Determiner\AttributeIsIndexableCondition` as an example of a condition.

[title] Pipelines Customisation
[path] Indexing/Entities/Sync/Pipelines/

Making customisations to existing Klevu pipelines.

:::hint{type="warning"}
Before adding attributes to your pipeline YAML, please ensure they have been [registered with Klevu](https://docs.klevu.com/klevu-magento-v4/attributes#DaeAe).
:::

:::hint{type="info"}
Note: any customisations made via these methods will override the auto-generated pipeline configuration files found in `var/klevu/indexing/pipeline`

During development, it may be useful to edit (in a non-production environment) these auto-generated YAML files to test out customisations before copying the YAML to a custom override file.&#x20;

These files will be regenerated and can be deleted once the customisation override has been created.
:::

## Adding Pipeline Stages

:::hint{type="info"}
Note: All these examples could be combined into one `pipelineConfigurationOverrideFilepaths` file.&#x20;

They have been split into multiple files, as we do in the modules, to make them easier to read.
:::

### Example 1:

Add `meta_description` and `meta_title` to the default (simple, virtual, downloadable product types) product data during the Add action.

First, in your module add or update `etc/di.xml`.&#x20;
Add a virtual type for `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add` and pass in an array of `pipelineConfigurationOverrideFilepaths`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="defaultProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_default.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

If the same changes are required during an Update (almost always the case) then we’d also make the same change to `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="defaultProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_default.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create the YAML file.

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update\_default.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
           stages:
             default: # Product type
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        addStages: # add attribute data to the existing pipeline
                                   # add stages accepts an array of stages to be added
                          meta_description:
                            import: Vendor_Module::etc/pipeline/product/attributes/meta_description.yml
                          meta_title:
                            import: Vendor_Module::etc/pipeline/product/attributes/meta_title.yml
```
:::

And add the 2 referenced file (this code could also be added to the above YAML, but it is more readable when split into multiple files)

:::CodeblockTabs
Vendor/Module/etc/pipeline/product/attributes/meta\_description.yml

```yaml
stages:
  getValue:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getMetaDescription()
      transformations:
        - StripTags(null, ["script"])
        - EscapeHtml
        - toString
```
:::

:::CodeblockTabs
Vendor/Module/etc/pipeline/product/attributes/meta\_title.yml

```yaml
stages:
  getValue:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getMetaTitle()
      transformations:
        - EscapeHtml
        - toString
```
:::

### Example 2:

Add `color` and `size` to configurable variant product data during the sync action.

First, in your module add or update `etc/di.xml`.&#x20;
Add a virtual type `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add` and pass in an array of `pipelineConfigurationOverrideFilepaths`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="variantProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_variant.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

If the same changes are required during an Update then we’d also make this change to `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="variantProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_variant.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create the YAML file.

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update\_variant.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
           stages:
             variantProduct: # Product type
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        addStages: # add attribute data to the existing pipeline
                                   # add stages accepts an array of stages to be added
                          color:
                            import: Vendor_Module::etc/pipeline/product/attributes/color.yml
                          size:
                            import: Vendor_Module::etc/pipeline/product/attributes/size.yml
```
:::

And add the 2 referenced file (this code could also be added to the above YAML, but it is more readable when split into multiple files)

:::CodeblockTabs
Vendor/Module/etc/pipeline/product/attributes/color.yml

```yaml
stages:
  getValue:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::
      transformations:
        - GetAttributeText("color")
        - ToString
        - Trim
```
:::

:::CodeblockTabs
Vendor/Module/etc/pipeline/product/attributes/color.yml

```yaml
stages:
  getValue:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::
      transformations:
        - GetAttributeText("size")
        - ToString
        - Trim
```
:::

***

## Updating Existing Pipeline Stages

This works the same as adding a new pipeline stage. In this example, we will append extra data to the `description`.

First, in your module add or update `etc/di.xml`.&#x20;
Add a virtual type `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add` and pass in an array of `pipelineConfigurationOverrideFilepaths`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="defaultProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_default.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

If the same changes are required during an Update then we’d also make this change to `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="variantProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_default.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create the YAML file.

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update\_default.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
           stages:
             default: # Product type
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        addStages: # can also be used to override existing stage definitions 
                          description:
                            import: Vendor_Module::etc/pipeline/product/attributes/description.yml
```
:::

Append the product name and sku to the end of the description

:::CodeblockTabs
Vendor/Module/etc/pipeline/product/attributes/description.yml

```yaml
stages:
  getValue:
    pipeline: Stage\Extract
    args:
      extraction: currentProduct::getDescription()
      transformations:
        - Append(" - ", $currentProduct::getName(), " - ", $currentProduct::getSku())
        - StripTags(null, ["script"])
        - EscapeHtml
```
:::

***

## Removing Pipeline Stages

In this example, we will remove the `rating` and `rating count` from any configurable variant so indexing falls back to using the parent values

First, in your module add or update `etc/di.xml`.&#x20;
Add a virtual type `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add` and pass in an array of `pipelineConfigurationOverrideFilepaths`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="variantProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_variant.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

If the same changes are required during an Update then we’d also make this change to `Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths"
                  xsi:type="array">
            <item name="variantProductCustomisation"
                  xsi:type="string">Vendor_Module::etc/pipeline/add_update_variant.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

Create the injected customisation YAML file

:::CodeblockTabs
Vendor/Module/etc/pipeline/add\_update\_variant.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
           stages:
             variantProduct: # Product type
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        removeStages: # remove attribute data from the existing pipeline
                          # remove stages accepts an array of stages to be removed
                          - rating
                          - ratingCount
```
:::

***

## Example Module

An example module with YAML files for common attributes that could be useful.
Contains examples of how to:

- change data synced for existing attributes
- add stages to pipelines
- add different attributes for different products types.
- add new product types
- remove attributes
- remove attributes from data if some condition is met (in this case if the value is null)

List of attribute YAML files present in the module

- `color`
- `gender`
- `manufacturer`
- `meta_description`
- `meta_keywords`
- `meta_title`
- `new`
- `sale`
- `size`
- `weight`

::File[]{src="https://archbee-doc-uploads.s3.amazonaws.com/Y9Igf1t4Mq0XfqFm13RFY-jKmL7VokEtV1f07JZnak0-20241203-170853.zip" label="Example_CustomisePipelineData.zip"}

:::hint{type="danger"}
This is not a production ready module and is intended as an example only.

**Do not install this module in a production environment.**
:::






[title] Configuring a Custom Product Indexing Batch Size
[path] Common Customisations/

## Configuring a Custom Product Indexing Batch Size

The product indexing module defines a batched entity provider using Magento dependency injection in `etc/di.xml`.

By default, the batch size is configured on the following virtual type:

- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched`

This virtual type sets the constructor argument:

- `batchSize`

and the module assigns it the default value:

- `Klevu\Indexing\Constants::DEFAULT_INDEXING_BATCH_SIZE`

### How to override the batch size

To use a custom batch size, add a DI override in your custom module’s `etc/di.xml` and set a numeric value for the `batchSize` argument.

Example:

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched">
        <arguments>
            <argument name="batchSize" xsi:type="number">500</argument>
        </arguments>
    </type>

</config>
```

### Why this works

The module declares a shared batched provider:

- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched`

Other batched product provider variants inherit from it, including:

- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Simple`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Virtual`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Downloadable`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Bundle`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Grouped`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\Configurable`
- `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched\ConfigurableVariants`

Overriding the shared `Batched` type updates the batch size used by all of these, unless a more specific subtype override is also declared.

### Example use case

If you want to increase the number of products processed in each batch during discovery, set a larger value such as:

```xml
<argument name="batchSize" xsi:type="number">500</argument>
```

If you want smaller, more conservative processing batches, use a lower value.

### Notes

- The value must be numeric.
- This change should be added in a custom module, not by editing the vendor module directly.
- After updating DI configuration, run the appropriate Magento cache/compiled dependency refresh steps for your environment.

### Summary

To pass a custom `batchSize`, override this DI argument in your custom module:

- Type: `Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched`
- Argument: `batchSize`

Example:

```xml
<type name="Klevu\IndexingProducts\Service\Provider\ProductEntityProvider\Batched">
    <arguments>
        <argument name="batchSize" xsi:type="number">500</argument>
    </arguments>
</type>
```


[title] Product Attribute Data Is Not Synced To Klevu Indexes
[path] Troubleshooting/

# Problem

Attribute data for product records is not showing in Klevu indexed data

# Potential Causes

## Attribute Is Not Registered With Klevu

If an attribute is not registered with Klevu before data is sent, the request will be considered invalid and the payload will not be processed.

If this is a standard Magento attribute, first of all ensure that the Register with Klevu setting is enabled in the Manage Attributes page (*Stores > Attributes > Product*)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/VQVkHnqBI9WJd52U_Jrql-20251001-134538.png)

Next, you can check which attributes exist at the Klevu side for any integrated API key by visiting the Klevu Information section (*Stores > Configuration > Klevu > Information > Indexing > Attributes > Klevu Attributes*)

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/V1UjKsVL2TWlnnZu_Okht-20251001-150144.png)

## Product Has Not Been Synced With Klevu

You can easily check the last sync activity for individual records via the Magento products grid (Catalog > Products). In each product row, under the “Select” dropdown in the Action column, you will find a “Klevu Sync Info” link.&#x20;

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/AfdG4QfYaou2UYb4KLnV2-20251001-150243.png)

Clicking this link will show all recorded sync activity for that record across all integrated API keys.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/bxsezu-vj_YE-GZGxAiq3-20251001-150318.png)

There are a number of reasons a product may not be picked up for sync which are out of scope of this article. If running entity discovery / update and triggering a sync does not send the record, please contact our support team for help.

## Product Synced But Rejected Or Dropped By Klevu Indexers

If data is being included in the indexing API payload but doesn’t appear in the indexed data in Klevu, there may be issues with the data itself, or issues with other products within the same batched payload.

In the Entity Sync Information screen (shown above), you can see the status of each sync attempt which included this record.
If sync is not being performed successfully, please enable verbose indexing logging (*Stores > Configuration > Klevu > Developer Settings > Logging > Indexing Log Level*); trigger a sync; and contact our support team with the relevant log file(s) for help.

## Product Synced Successfully But Does Not Contain Attribute

If product records are being received successfully by Klevu’s indexers, you can validate the payload sent to the API by enabling verbose indexing logging (*Stores > Configuration > Klevu > Developer Settings > Logging > Indexing Log Level*); triggering a sync; and checking the resulting indexing log file (at var/log/klevu/\{storeCode}/klevu-\{storeCode}-indexing.log).

You are looking for DEBUG lines containing the string “Chunked payload”, which will contain the request payload in the context

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/AfxZWchThQ8g9ThBHQEcm-20251001-150433.png)

If the attribute code is not present in the payload, ensure that the pipeline configuration contains the relevant extraction stage(s) for this attribute.

The following command in the Magento CLI will generate a dump of the entire product add / update process. In our example, we write the output to a file in the var directory, as pipeline configuration can contain thousands of lines.

```bash
$ bin/magento klevu:indexing:configuration-dump-pipeline KLEVU_PRODUCT::add > var/KLEVU_PRODUCT.add.yml
```

If the attribute code is present, please contact our support team for further help, including both the indexing logs and generated pipeline configuration.

If the attribute code is not present, or only present for a subset of products, ensure that automatic pipeline generation is enabled for this attribute via *Stores > Attributes > Product* and checking the **Automatically Generate Pipeline Configuration For** setting.&#x20;

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/0tRUqsm-wEeTL3E2V1iTl-20251001-150541.png)

You should see every product type that should contain this attribute data selected.
If any are missing, update the field configuration and save the attribute; and then trigger entity update and sync operations, which should now contain the missing attribute.

:::hint{type="info"}
When managing attribute configuration, we need to both register the attribute with Klevu so that the receiving end expects this data and knows how to process it, as well as including this data in the payload we send across.

We do not automatically assume you will want to sync attribute data for any product type in order to provide you with as much control over your data synchronisation as possible.
For example, you may explicitly not want to send data for certain product types (one use case would be excluding configurable parents to avoid potential unwanted data inheritance); alternatively, you may wish to define your own extraction; transformation; and validation stages (as detailed here: [Changing Attribute Data Sent to Klevu Indexes](docId\:Dzq7yw9jLJR6lL1U-Pm3U) )
:::

If the attribute is still not present in the payload following these changes, please contact our support team for further help, including both the indexing logs and (re)generated pipeline configuration.

[title] Removed Features
[path] Klevu Module v4.x Overview/

## v2.x/v3.x Features No Longer Supported

These features from v2.x/v3.x have not been migrated to v4.x and will not be added in the future.

### Theme JSv1

JSv1 is deprecated and therefore not supported in v4.x. Merchants using JSv1 in v2.x/v3.x have the choice of either remaining on v2.x/v3.x or migrating to JSv2.

### Checkout Analytics

Triggering analytics requests for sales data from the checkout success page in the Luma theme via JavaScript. This didn't cover all themes or checkouts, e.g. Hyvä Checkout. No longer be required given changes made to analytics requests sent via the PHP-SDK.

### Lazy Load JS Libraries

This improved Lighthouse scores but degraded performance for the customer.

[title] Order Sync History
[path] Analytics/

As shown in the Order View screen, a history of sync actions performed for this order is retained. History items are saved to the `klevu_sync_order_history` database table and contain the following information

- Date and time the action was performed
- What action was taken (for example, queueing for sync; starting processing)
- The initiator of the action (for example, the Order save event; CLI command)
- Whether the action completed successfully
- A JSON-encoded string of additional information. This information varies based upon the action performed; initiator; etc, but generally will contain the following details
  - The Magento order id
  - The Magento store id
  - Sync status before the action was performed
  - Sync status after the action completed

## Pruning History Records

By default, all history records are retained indefinitely. For stores with high order volume, this may introduce performance and storage concerns and the number of records builds up. As such, the module can be configured to prune old records automatically.

To enable order history pruning, enter values in one or both of the following configuration settings

- **Klevu** > **Developer Settings** > **Order Analytics** > **Remove History for Successfully Synced Orders After (days)**
- **Klevu** > **Developer Settings** > **Order Analytics** > **Remove History for Failed Synced Orders After (days)**

These values will determine the number of days for which to hold onto sync history for orders in the following statuses respectively: “complete”, “error”. Orders which are still pending synchronisation (including those which have been requeued) will not have history records removed.
Note, this setting is global, meaning you cannot configure different thresholds based upon store.

:::hint{type="info"}
Sync history is pruned based upon the timestamp of the history item, not the order date, meaning orders where processing spans multiple days may show partial history.&#x20;
:::

Sync history pruning is performed by the `klevu_analytics_remove_synced_order_history` cron job, which is scheduled to run at midnight each day.

[title] FAQs and Troubleshooting
[path] Indexing/

### I can’t see synced data in the log files.

By default, all logs are set to “Standard” `Monolog\Logger::INFO`.&#x20;
To see indexing data in the logs set the Indexing logger to “Verbose” `Monolog\Logger::DEBUG`.
That setting can be found here `Stores > Configuration > Klevu > Developer Settings > Logging`.

***

### I have integrated my store, but no entity data has been indexed to Klevu.

Attribute discovery and attribute sync are triggered on integration as is entity discovery. Entity sync however is handled via cron. Please ensure you have corn running correctly. The indexing cron default schedule is set to every 30 minutes. This can be customised in the admin `Stores > Configuration > Klevu > Data Sync > Indexing`

:::hint{type="info"}
As with all cron tasks added by version 4.x of the Klevu integration, order sync cron tasks use the dedicated `klevu` cron group, allowing granular configuration of scheduling and run options.

We recommend using the native Magento cron to run these jobs, configuring schedules if necessary, rather than a custom server-side cron implementation of the CLI command.
:::

***

### How do I exclude certain products/categories/CMS pages from the index?

By default, Klevu will index all enabled products/categories/CMS pages. There are [admin settings](https://docs.klevu.com/klevu-magento-v4/entities-pipelines-customisation) to exclude disabled products/categories/CMS pages or out-of-stock products. If you wish to exclude entities from the sync based on any other attribute you can add an [is indexable condition to the determiner](https://docs.klevu.com/klevu-magento-v4/entities-is-indexable-determiner) via `etc/di.xml`.

***

### How do I exclude products from indexing by visibility?

By default, we do not filter products by visibility when indexing data. We have an optional module that can be installed to add the ability to filter products on visibility before indexing.

:::hint{type="warning"}
We have 2 future releases planned:

- integrate your auth keys at website scope (same auth keys for multiple stores).
- indexing visibility for customer groups.

This module would cause issues with either setup as products could have differing visibility between stores and customer groups, potentially triggering a `Delete` request when the product should be sent to Klevu.
:::

The module can be installed via composer or found on [Github](https://github.com/klevu/module-m2-indexing-products-exclude-by-visibility)

```shell
composer require "klevu/module-m2-indexing-products-exclude-by-visibility"
```

The frontend modules filter search requests based on visibility which matches the default Magento behaviour

- `category-search or search` for search requests.
- `category-search or category` for category navigation requests.

***

### How do I sync all products/categories/CMS pages?

The Klevu modules always send a delta sync, i.e. just the products that need to be updated. Which products to send to Klevu is determined by the `next_action` column in the `klevu_indexing_entities`.&#x20;
We have a [CLI command to set entities to require an update](https://docs.klevu.com/klevu-magento-v4/indexing-cli#yAHBO) (or addition/deletion if applicable). In that command instead of passing a list of IDs to update we can pass `--entity-ids="all"`. This will set all entities, that are indexable, to require an update. These entities will be synced to Klevu on the next cron run or the sync can be triggered via the [sync CLI command](https://docs.klevu.com/klevu-magento-v4/entities-sync#7D59x).

***



### Why are configurable and variant products indexed as out-of-stock when they are in stock?

In Magento `2.4.4` -  `2.4.6-p7`, there is a bug in Magento MSI where a configurable product became out of stock it would not come back into stock, even if the admin displayed Stock Status: In Stock.
This [issue](https://github.com/magento/magento2/issues/36421) was fixed in the [2.4.7 release](https://experienceleague.adobe.com/en/docs/commerce-operations/release/notes/adobe-commerce/2-4-7?lang=en#inventory-management-1) and can be applied via [quality patch ID: ACSD-56546](https://experienceleague.adobe.com/tools/commerce-quality-patches/index.html?keyword=ACSD-56546).
If that does not fix the issue, please review the 2.4.7 release as there were multiple inventory issues fixed in that release.

### How stock info indexed for products and variants?


[title] Anchor Categories
[path] Indexing/Entities/Categories/

Out of the box, the Klevu plugin respects the `is_anchor` category setting.

To change this behaviour and ignore anchor categories you can add a before plugin on `ParentAnchorCategoryIdProvider` and return an empty array.

```xml
<type name="Klevu\IndexingProducts\Service\Provider\Catalog\ParentAnchorCategoryIdProvider">
  <plugin name="Vendor_Module::ParentAnchorCategoryIdProvider"
          type="Vendor\Module\Plugin\Service\Provider\Catalog\ParentAnchorCategoryIdProviderPlugin"/>
</type>
```

Create the Plugin class.

:::CodeblockTabs
Vendor/Module/Plugin/Service/Provider/Catalog/ParentAnchorCategoryIdProviderPlugin.php

```php
<?php

namespace Vendor\Module\Plugin\Service\Provider\Catalog;

use Klevu\IndexingApi\Service\Provider\Catalog\ParentAnchorCategoryIdProviderInterface;

class ParentAnchorCategoryIdProviderPlugin
{
    /**
     * @param ParentAnchorCategoryIdProviderInterface $subject
     * @param int[] $categoryIds
     *
     * @return int[]
     */
    public function beforeGet(
        ParentAnchorCategoryIdProviderInterface $subject,
        array $categoryIds,
    ): array {
        return [[]];
    }
}
```
:::

Setting `categoryIds` param as an empty array will return an empty array skipping any extra database calls.

[title] Registering Transformers
[path] Indexing/Entities/Sync/Pipelines/

When creating transformers in a custom module we must register them with the pipelines.

Add the namespace for your transformer directory (e.g. `Vendor\Module\Pipeline\Transformer`) to the namespaces argument for the TransformerManager.&#x20;

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\PlatformPipelines\ObjectManager\TransformerManager">
    <arguments>
        <argument name="namespaces" xsi:type="array">
            <!-- Change the name of this item to match the directory containing your transformer classes -->
            <item name="Vendor\Module\Pipeline\Transformer"
                  xsi:type="const">Klevu\Pipelines\ObjectManager\ObjectManagerInterface::PRIORITY_NAMESPACE_SORT_ORDER</item>
        </argument>
    </arguments>
</type>
```
:::


[title] Category Attributes
[path] Indexing/Attributes/

Magento has separate attributes for categories and products and these can have the same attribute codes. e.g. `name` or `description`. For Klevu standard attributes this is not an issue, however, for custom attributes, this could lead to name clashes in Klevu. Therefore any custom category attribute will be prefixed with `cat__`. Product attributes remain unchanged.
e.g.&#x20;
a product attribute `list` would be registered as `list`&#x20;
a category attribute `list` would be registered as `cat__list`

Please keep this in mind when creating pipeline YAML files to sync categories.

[Indexing - Categories | Custom Attributes Name Prefix](https://docs.klevu.com/klevu-magento-v4/entities-custom-attributes-name-prefix)

[title] Magento Implementation
[path] Indexing/Entities/Sync/Pipelines/

When we trigger a sync from Magento, whether via cron or CLI, `Klevu\Indexing\Service\EntitySyncOrchestratorService::execute` is executed.&#x20;

This loops through all `entityIndexerServices`.&#x20;

These `entityIndexerServices` are injected via `di.xml` from each entity indexing module  (`module-m2-indexing-categories`, `module-m2-indexing-cms`, `module-ms-indexing-products`).

e.g. from `module-ms-indexing-products/etc/di.xml`

```xml
<type name="Klevu\Indexing\Service\EntitySyncOrchestratorService">
    <arguments>
        <argument name="entityIndexerServices" xsi:type="array">
            <item name="KLEVU_PRODUCT" xsi:type="array">
                <item name="add"
                      xsi:type="object">Klevu\IndexingProducts\Service\EntityIndexerService\Add</item>
                ...
            </item>
        </argument>
    </arguments>
</type> 
```

The injected `EntityIndexerService` is a virtual type, into which we pass an `EntityIndexingRecordProvider` and a pipeline YAML file.

```xml
<virtualType name="Klevu\IndexingProducts\Service\EntityIndexerService\Add"
             type="Klevu\IndexingProducts\Service\EntityIndexerService">
    <arguments>
        <argument name="entityIndexingRecordProvider"
                  xsi:type="object">Klevu\IndexingProducts\Service\Provider\Sync\EntityIndexingRecordProvider\Add</argument>
        <argument name="pipelineConfigurationFilepath"
                  xsi:type="string">Klevu_IndexingProducts::etc/pipeline/add_update.yml</argument>
    </arguments>
</virtualType> 
```

:::hint{type="info"}
The `EntityIndexingRecordProvider` will provide the records to index.
The `pipelineConfigurationFilepath` contains the default yaml file containing instructions on how to process those records.
:::


[title] Logging
[path] /

We have split the logs into 4 areas to make them easier to consume (configuration, frontend, indexing and analytics). If a merchant has an indexing issue then a lot of frontend logging in that file is not helpful. Each logging area has different log levels `Errors only`, `Standard` and `Verbose`, i.e. verbose logging can be enabled for indexing while frontend logging remains errors only.

To make changes to logging settings, download, archive or clear logs navigate to `Stores > Configuration > Klevu > Developer Settings > Logging`

Switch to store view scope to zip and download all the logs for that store. You can also archive the logs (zip them up and move them to a different location on the server) and clear logs (delete all archived logs).

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/7TCQMm6VP_e0cTXa28iNJ_screenshot-2024-03-26-at-095329.png "Config Logging Settings")


[title] Incorrect Stock Status with Multi-Source Inventory
[path] Troubleshooting/

# Problem

When using Magento’s *Multi-Source Inventory* , you may encounter scenarios where the stock status synced with Klevu doesn’t match the availability in the webstore.&#x20;

# Potential Solutions

## Replace “Is Available” Check With “Is Salable”

Often, the problem can be traced to the Klevu integration checking whether is a product is available, rather than is salable, in the pipeline extraction.

We can validate this as a root cause with a small modification to the pipeline responsible for extracting product data, modifying the in\_stock extract for products and variants found in the following locations:

- *https\://github.com/klevu/module-m2-indexing-products/blob/main/etc/pipeline/product/attributes/in\_stock.yml*
- *https\://github.com/klevu/module-m2-indexing-products/blob/main/etc/pipeline/product/attributes/in\_stock/variant.yml*&#x20;

The specifics of modifying attribute data via pipeline customisations can be found in the following article: [Changing Attribute Data Sent to Klevu Indexes](docId\:Dzq7yw9jLJR6lL1U-Pm3U)

### Override the Extraction Method for Stock Status

Following the above article’s steps:

1\. The YAML paths we need to modify are

- For Variant Products
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.variantProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.checkStock.stages.getParentStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.variantProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.checkStock.stages.getVariantStock`
- For All Other Product Types
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.configurableProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.groupedProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.bundleProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.virtualProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.downloadableProduct.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`
  - `stages.iterateIndexingRecordsBatch.stages`
    `.iterateIndexingRecords.stages.processProduct.stages`
    `.default.stages.generateRecord.stages.attributes.stages`
    `.inStock.stages.getStock`

2\. The change required is to change the extraction method from `::isAvailable()` to `::isSalable()`

3\. Express the changes as YAML

- Variant Products

```yaml
stages:
  inStock:
    stages:
      checkStock:
        stages:
          getParentStock:
            pipeline: Stage\Extract
            args:
              extraction: 'currentParentProduct::isSalable()'
          getVariantStock:
            pipeline: Stage\Extract
            args:
              extraction: 'currentProduct::isSalable()'
              transformations: ToBooleany
```

:::hint{type="info"}
As the `getParentStock` stage essentially acts as a guard clause, you may not want or need to override this stage, depending on your site’s set up.&#x20;
:::

- All Other Product Types

```yaml
stages:
  inStock:
    stages:
      getStock:
        pipeline: Stage\Extract
        args:
          extraction: 'currentProduct::isSalable()'
          transformations: ToBoolean
```

4\. Implement the changes in a local or staging environment
The easiest way is to add the above snippets under the attributes path for each applicable product type under var/klevu/indexing/pipeline/product/add\_update.overrides.yml and trigger a sync. As this file is already registered, it will not require a recompilation before testing, allowing faster feedback on whether the change addresses the issue.

5\. Transfer the changes to a dedicated customisation module

Complete YAML override based on above

*Suggested filepath within module:* `etc/pipeline/indexing/product/add_update.overrides.yml`

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
            stages:
              variantProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              checkStock:
                                stages:
                                  getParentStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentParentProduct::isSalable()'
                                  getVariantStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              configurableProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              groupedProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              bundleProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              virtualProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              downloadableProduct:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
              default:
                stages:
                  generateRecord:
                    stages:
                      attributes:
                        stages:
                          inStock:
                            stages:
                              inStock:
                                stages:
                                  getStock:
                                    pipeline: Stage\Extract
                                    args:
                                      extraction: 'currentProduct::isSalable()'
                                      transformations: ToBoolean
```

And registration changes to be added to `etc/di.xml`

```xml
    <virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
        <arguments>
            <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
                <item name="vendor_klevuindexingstockstatus_indexing_product_add_update"
                      xsi:type="string">Vendor_KlevuIndexingStockStatus::etc/pipeline/indexing/product/add_update.overrides.yml</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
        <arguments>
            <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
                <item name="vendor_klevuindexingstockstatus_indexing_product_add_update"
                      xsi:type="string">Vendor_KlevuIndexingStockStatus::etc/pipeline/indexing/product/add_update.overrides.yml</item>
            </argument>
        </arguments>
    </virtualType>
```

6\. Deploy the customisation module to production; requeue any affected products; and trigger an entity sync

:::hint{type="success"}
Sample module: [Vendor\_KlevuIndexingStockStatus on Github](https://github.com/klevultd/m2-customisations/tree/main/Vendor_KlevuIndexingStockStatus)
:::


[title] Untitled
[path] /


[title] Changing Attribute Data Sent to Klevu Indexes
[path] Common Customisations/

## TL;WR

1\. Identify the YAML path(s) to the attribute you wish to modify
Eg: `stages.iterateIndexingRecordsBatch.stages.iterateIndexingRecords.stages.processProduct.stages.virtualProduct.stages.attributes.shortDescription`

2\. Determine the changes required to alter the attribute output
Eg: Change the source data from using `short_description` to `meta_description`, or append a string

3\. Express the changes as YAML overrides
Eg, replacing *just* the specific extraction stage:

```yaml
stages:
  generateData:
    stages:
      default:
        getDefaultLanguageValue:
          stages:
            getData:
              stages:
                extract:
                  pipeline: Stage\Extract
                  args:
                    extraction: currentProduct::getMetaDescription()
                    transformations:
                      - StripTags(["p", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "ul", "ol", "li", "dl", "dt", "dd", "img", "sub", "sup", "small"], ["script"])
                      - EscapeHtml
                      - Trim
```

or appending additional data

```yaml
stages:
  generateData:
    stages:
      default:
        getDefaultLanguageValue:
          stages:
            getData:
              addStages:
                after: validate
                transform:
                  pipeline: Stage\Transform
                  args:
                    transformation: Append(" - This is a very special product.")
```

4\. Implement the changes in a **local** or **staging** environment
Eg, add the YAML overrides under the identified attribute path in the `var/klevu/indexing/pipeline/product/add_update.overrides.yml` file and set off a sync

5\. Transfer changes to a dedicated customisation module, including creation of specific overrides files, and registration via di.xml
Eg,

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
            stages:
              virtualProduct:
                stages:
                  attributes:
                    shortDescription:
                      stages:
                        generateData:
                          stages:
                            default:
                              stages:
                                getDefaultLanguageValue:
                                  stages:
                                    getData:
                                      stages:
                                        extract:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/extract.yml
                                      addStages:
                                        after: validate
                                        transform:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/transform.yml
```

:::CodeblockTabs
di.xml

```xml
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
            <item name="vendor_klevuindexingoverrides_indexing_product_add_update"
                  xsi:type="string">Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/add_update.overrides.yml</item>
        </argument>
    </arguments>
</virtualType>
<virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
    <arguments>
        <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
            <item name="vendor_klevuindexingoverrides_indexing_product_add_update"
                  xsi:type="string">Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/add_update.overrides.yml</item>
        </argument>
    </arguments>
</virtualType>
```
:::

6\. Deploy the customisation module to production; requeue any affected products; and trigger an entity sync

***

## Background

The Klevu Magento integration uses a pipeline system where product records are fed in, converted into a JSON representation, pushed to Klevu via API, and the result returned for processing by the application.

These pipelines are defined using one or more YAML files, compiled into a single set of instructions designed to be human readable and easily customisable.

:::hint{type="info"}
You can view a comprehensive list of YAML config files used to generate all pipelines with the following command

```shell
php bin/magento klevu:pipelines:configuration-debug list-files
```
:::

:::hint{type="info"}
You can view the full, compiled configuration for any (indexing) pipeline using the following command (where `<pipelineIdentifier>` is replaced with the actual pipeline, eg `KLEVU_PRODUCT::update` for the product update pipeline

```shell
php bin/magento klevu:indexing:configuration-dump-pipeline <pipelineIdentifier>
```

*Generated pipelines can be thousands of lines long - we recommend piping the output into a temporary file in&#x20;*`var`*&#x20;to reference more easily*

This output is the most reliable way of identifying the paths required (including for custom attributes) to modify stages via overrides - which we will need in this guide
:::

Generation of all attribute data - including extraction and transformation - can be found in these pipelines, separated into various stages which can be removed or replaced with a small bespoke module.

:::hint{type="info"}
These changes can also be incorporated into existing customisation modules, though we recommend keeping customisations separate to allow easier maintenance, debugging, and removal if required.
:::

:::hint{type="warning"}
Changes can be made directly to the autogenerated `var/klevu/*/pipeline/*/*.overrides.yml` files (for example `var/klevu/indexing/pipeline/product/add_update.overrides.yml` file, for product indexing add and update operations).

While this is a valid way of quickly testing a change in a non-production environment, be aware that any files in var are intentionally transitory and modifications should be moved to a permanent location within a separate extension before pushing to production
:::

### Identifying the YAML Configuration Path

:::hint{type="info"}
For this guide, we will be assuming you are changing a product attribute. Category and CMS pipelines can be modified in the same manner, though you should use `KLEVU_CATEGORY` / `KLEVU_CMS` identifiers instead of `KLEVU_PRODUCT` .
:::

The first step is to identify the full YAML path to the attribute you wish to modify. We can do this by referencing the parent *add\_update.yml* file and its included children, or generate a configuration dump and trace the path through the consolidated file (the more reliable option).

:::hint{type="info"}
When reading a path, we record the name of the stage and then its stages node, which tells the system that there are child pipelines to to be processed.

For example:

```yaml
stages:
  logStart:
    pipeline: Indexing\Stage\Log # log that the pipeline has begun
    args:
      message: "Start Add/Update Products Pipeline"
  iterateIndexingRecordsBatch:
    pipeline: Pipeline\Iterate # LOOP OVER ALL PROVIDED BATCHES
    args:
      continueOnException: ~
    stages:
      iterateIndexingRecords:
        pipeline: Pipeline\Iterate # LOOP OVER ALL PROVIDED RECORDS
        args:
          continueOnException: ~
        stages:
          processIndexingRecordStart: # set some variables before processing product data
```

This snippet gives us various paths, culminating in `stages.iterateIndexingRecordsBatch.stages.iterateIndexingRecords.stages.processIndexingRecordStart`
More clearly illustrated as&#x20;

```yaml
stages:
#  logStart:
#    pipeline: Indexing\Stage\Log # log that the pipeline has begun
#    args:
#      message: "Start Add/Update Products Pipeline"
  iterateIndexingRecordsBatch:
#    pipeline: Pipeline\Iterate # LOOP OVER ALL PROVIDED BATCHES
#    args:
#      continueOnException: ~
    stages:
      iterateIndexingRecords:
#        pipeline: Pipeline\Iterate # LOOP OVER ALL PROVIDED RECORDS
#        args:
#          continueOnException: ~
        stages:
          processIndexingRecordStart: # set some variables before processing product data
```
:::

We’re initially looking for the `processProduct` stage, which will perform different steps depending on the product type being processed.
At time of writing, this path is: `stages.iterateIndexingRecordsBatch.stages.iterateIndexingRecords.stages.processProduct`
*Reference:&#x20;*[module-m2-indexing-products/etrc/pipeline/add\_update.yml](https://github.com/klevu/module-m2-indexing-products/blob/main/etc/pipeline/add_update.yml#L62)

We will need to record the paths for each of the different product types that this modification will support (eg `…stages.variantProduct`).

Within each product, attribute output definitions are defined at `...stages.attributes`, with an identifier corresponding to the Klevu attribute name (eg `…stages.shortDescription`).
This stage should receive the current product object as its payload, which is passed through the defined child stages, and the output is the generated value which will be sent to Klevu’s indexes.

:::hint{type="info"}
As a rule, core attributes' definitions can be found in individual YAML files which are included into the main pipeline. This allows us to re-use the same steps for different product types, as well as giving an easy reference point if you ever need to check how Klevu generates an attribute value.

*Reference:&#x20;*[module-m2-indexing-products/etc/pipeline/product/attributes](https://github.com/klevu/module-m2-indexing-products/tree/main/etc/pipeline/product/attributes)
:::

### Before Making Our Changes

Before we make our changes, a quick reminder of the different types of pipeline stage you may wish to use or replace

- `Stage\Extract` : extracts a value from the passed payload (or, in many cases, from context - such as grabbing an attribute value from the current product object)
  May contain transformations
- `Stage\Transform` : passes the passed payload through one or more transformation functions (each transformation maps to a PHP class of the same name)
- `Stage\Validate` : validates the passed payload against one or more conditions, throwing an exception on failure (which may be caught and handled, or left to break an iteration or the pipeline overall)
- `Pipeline\Fallback` : a parent pipeline containing multiple stages intended to be validated and, on failure, fall back to the next stage&#x20;

Also, a quick reminder of the override operations we can perform on an existing pipeline stage (this applies to *any* pipeline stage, not just those generating attribute values, and at any depth - allowing us to target specific parts of an attribute generation if required. Remember, the more specific we can be, the smaller the overall impact of our customisation)

- **Add** (`addStages`) : insert new stages before or after a named target (for example, adding an additional transformation)
- **Delete** (`removeStages`) : remove existing stages (for example, removing a case from a fallback pipeline)
- **Override** : Straight-up replace the targeted stage with a new definition

***

## Implementing the Customisation

Finally, we get to making a change, which involves the following steps

1. Identify the YAML path(s) to the attribute you wish to modify
2. Determine what changes we need to make
3. Implement and refine those changes in a staging environment
4. Transfer the changes to a customisation module and retest in a staging environment before deployment
5. Deploy changes, requeue affected products, and trigger an entity sync

:::hint{type="info"}
In our example, we are going to modify the way that the shortDescription attribute is generated for virtual and downloadable products only.

The changes we want to make are to

- Use the meta description attribute, rather than short description, as our source value
- Append the string “ - This is a very special product.” at the end of the generated value *if the meta description is not empty*
- Apply this change to virtual and downloadable product types
:::

### Identify the YAML path(s) to the attribute you wish to modify

- `stages.iterateIndexingRecordsBatch.stages.iterateIndexingRecords.stages.processProduct.stages.virtualProduct.stages.attributes.shortDescription`
- `stages.iterateIndexingRecordsBatch.stages.iterateIndexingRecords.stages.processProduct.stages.downloadableProduct.stages.attributes.shortDescription`

:::hint{type="info"}
If you don’t know how we got these paths, go re-read the **Identifying the YAML Configuration Path** section above.

*Reference:&#x20;*[module-m2-indexing-products/etc/pipeline/product/attributes/short\_description.yml](https://github.com/klevu/module-m2-indexing-products/blob/main/etc/pipeline/product/attributes/short_description.yml)**
:::

### Determine the changes required to alter the attribute output

- **Change** the extraction from `currentProduct::getShortDescription()` to `currentProduct::getMetaDescription()`
- **Add** a Stage\Transform stage after the validation to Append a value
  *Note: as we are replacing the the&#x20;*&#x65;xtrac&#x74;*&#x20;stage, it might be tempting to add the Append to the list of transformation arguments and save a change. This, however, would make our Validate stage worthless as every passed value would contain our appended string*

### Express the changes as YAML overrides

To change the extraction, we need to replicate the entire extract stage definition as we can’t just replace a stage’s property.&#x20;
Taking the definition [from the core code](https://github.com/klevu/module-m2-indexing-products/blob/main/etc/pipeline/product/attributes/short_description.yml#L12), replace getShortDescription() with getMetaDescription()

```yaml
pipeline: Stage\Extract
args:
  extraction: currentProduct::getMetaDescription()
  transformations:
    - StripTags(["p", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "ul", "ol", "li", "dl", "dt", "dd", "img", "sub", "sup", "small"], ["script"])
    - EscapeHtml
    - Trim
```

To append data, we need a new stage of type `Stage\Transform` with a transformation of type [Append](https://github.com/klevu/php-pipelines/blob/master/src/Transformer/Append.php), passing in our desired string

```yaml
pipeline: Stage\Transform
args:
  transformation: Append(" - This is a very special product.")
```

:::hint{type="info"}
We’re using a static value here, but we could just as easily pass in a string from our context (for example, from the Magento configuration) or the existing product using an extraction here.
Eg

```yaml
pipeline: Stage\Transform
args:
  transformation: Append(" - ", $currentProduct.getMetaTitle())
```
:::

### Implement the changes in a **local** or **staging** environment

As we are making the changes on a staging (or local) environment, we can take advantage of the auto-generated files which contain our custom attribute definitions. By adding changes directly to (in this case) `var/klevu/indexing/pipeline/product/add_update.overrides.yml`, we don’t need to worry about building a module just to test a theory, or recompiling as the file is already included.

:::hint{type="warning"}
To be safe, you should disable the automatic regeneration of configuration overrides while working to ensure your changes don’t suddenly disappear.

In the Magento backend, set **Stores** > **Configuration** > **Klevu** > **Developer Settings** > **Pipelines** > **Enable autogeneration of configuration overrides&#x20;**&#x74;o “No” and clear your cache
:::

First, replicate the paths identified above in YAML format.&#x20;

**Note:** if you have autogenerated attribute information in the file, you can use the existing structure without having to remove or duplicate the paths (which would not be valid YAML)

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
            stages:
              virtualProduct:
                stages:
                  attributes:
                    shortDescription:
              downloadableProduct:
                stages:
                  attributes:
                    shortDescription:
```

and add the overrides required

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
            stages:
              virtualProduct:
                stages:
                  attributes:
                    shortDescription:
                      stages:
                        generateData:
                          stages:
                            default:
                              getDefaultLanguageValue:
                                stages:
                                  getData:
                                    stages:
                                      extract:
                                        pipeline: Stage\Extract
                                        args:
                                          extraction: currentProduct::getMetaDescription() # This is our change
                                          transformations:
                                            - StripTags(["p", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "ul", "ol", "li", "dl", "dt", "dd", "img", "sub", "sup", "small"], ["script"])
                                            - EscapeHtml
                                            - Trim
                                    addStages:
                                      after: validate
                                      transform:
                                        pipeline: Stage\Transform
                                        args:
                                          transformation: Append(" - This is a very special product.")
              downloadableProduct:
                # Implement the same for downloadable products
```

Now, queue one or more products for sync by updating the product data or via CLI

```shell
php bin/magento klevu:indexing:entity-update --entity-types=KLEVU_PRODUCT --entity-ids=1,2,3 -vvv
```

and trigger a sync

```shell
php bin/magento klevu:indexing:entity-sync --entity-types=KLEVU_PRODUCT -vvv
```

:::hint{type="info"}
We recommend enabling verbose indexing logging and archiving existing logs before triggering the test sync to make identifying the most recent data simpler
:::

### Transfer changes to a dedicated customisation module

:::hint{type="info"}
This guide assumes you are familiar with creating a Magento 2 extension.

If you work better with code in front of you to reference, there is an example module at the end of the article
:::

:::hint{type="warning"}
**IMPORTANT:&#x20;**&#x54;his example module is not production-ready and should not be used. It is for reference and illustration purposes only and no guarantee is made to its reliability.

We strongly recommend testing it in your own environment before deploying it to production.
:::

We will use the module name Vendor\_KlevuIndexingOverrides; you should choose a namespace (and module name) suited to your installation.

**Dependencies**

We will reference the **Klevu Indexing Products** and **PHP-Pipelines** packages, so ensure you include the following in the extension’s `composer.json` file

:::CodeblockTabs
composer.json

```json
    "require": {
        "php": "~8.1.0|~8.2.0|~8.3.0|~8.4.0",
        "klevu/module-m2-indexing-products": "^3.0.0",
        "klevu/php-pipelines": "^1.1.0"
    },
```
:::

and the following in the extension’s `etc/module.xml` file

:::CodeblockTabs
etc/module.xml

```xml
        <sequence>
            <module name="Klevu_IndexingProducts"/>
            <module name="Klevu_Pipelines"/>
        </sequence>
```
:::

**Pipeline YAML**

:::hint{type="info"}
Note, the framework isn’t opinionated about file locations, but we find the paths specified below are the most logical - especially as modules grow and include additional overrides, especially for different record types.
:::

We will create a parent overrides file at

- `etc/pipeline/indexing/product/add_update.overrides.yml` .&#x20;

The changes made above should be copied into this file, though to avoid duplication of code (especially if we need to make modifications to every product type), we will extract the actual changes to their own include files.
Create these files at

- `etc/pipeline/indexing/product/attributes/short_description/extract.yml`
- `etc/pipeline/indexing/product/attributes/short_description/transform.yml`

(if we were completely replacing the short\_description attribute’s definition, we could simply create `short_description.yml`, however keeping changes small and discrete means better maintainability in the future)

Our parent `add_update.overrides.yml` file should look like

:::CodeblockTabs
add\_update.overrides.yml

```yaml
stages:
  iterateIndexingRecordsBatch:
    stages:
      iterateIndexingRecords:
        stages:
          processProduct:
            stages:
              virtualProduct:
                stages:
                  attributes:
                    shortDescription:
                      stages:
                        generateData:
                          stages:
                            default:
                              stages:
                                getDefaultLanguageValue:
                                  stages:
                                    getData:
                                      stages:
                                        extract:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/extract.yml
                                      addStages:
                                        after: validate
                                        transform:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/transform.yml
              downloadableProduct:
                stages:
                  attributes:
                    shortDescription:
                      stages:
                        generateData:
                          stages:
                            default:
                              stages:
                                getDefaultLanguageValue:
                                  stages:
                                    getData:
                                      stages:
                                        extract:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/extract.yml
                                      addStages:
                                        after: validate
                                        transform:
                                          import: Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/attributes/short_description/transform.yml
```
:::

`extract.yml` should contain

:::CodeblockTabs
extract.yml

```yaml
pipeline: Stage\Extract
args:
    extraction: currentProduct::getMetaDescription() # This is our change
    transformations:
        - StripTags(["p", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "ul", "ol", "li", "dl", "dt", "dd", "img", "sub", "sup", "small"], ["script"])
        - EscapeHtml
        - Trim
```
:::

and `transform.yml`

:::CodeblockTabs
transform.yml

```yaml
pipeline: Stage\Transform
args:
    transformation: Append(" - This is a very special product.")
```
:::

**Defining the Overrides**

Now we need to tell the Klevu module to use these override files by injecting the `add_update.overrides.yml` filepath into the provider used when compiling our pipeline.&#x20;

In your `di.xml`, add

:::CodeblockTabs
di.xml

```xml
    <virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Add">
        <arguments>
            <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
                <item name="vendor_klevuindexingoverrides_indexing_product_add_update"
                      xsi:type="string">Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/add_update.overrides.yml</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="Klevu\IndexingProducts\Service\Provider\PipelineConfigurationOverridesFilepathsProvider\Update">
        <arguments>
            <argument name="pipelineConfigurationOverrideFilepaths" xsi:type="array">
                <item name="vendor_klevuindexingoverrides_indexing_product_add_update"
                      xsi:type="string">Vendor_KlevuIndexingOverrides::etc/pipeline/indexing/product/add_update.overrides.yml</item>
            </argument>
        </arguments>
    </virtualType>
```
:::

:::hint{type="info"}
Note that there are two providers - one for `KLEVU_PRODUCT::add` and `KLEVU_PRODUCT::update` operations. We have created a single pipeline overrides file for both operations, but if you need different values depending on whether a product is being sent to Klevu for the first time or not, you could create different overrides files and inject them to the relevant providers as required.
:::

**Compiling and Testing**

:::hint{type="warning"}
As we made our changes in the existing overrides file originally, we cannot reliably test our new module until we have reverted these updates.

To do this, ensure you have re-enabled the **Enable autogeneration of configuration overrides&#x20;**&#x63;onfig setting and cleared your cache.
Then, you can either modify an attribute through the Magento backend or force a regeneration via CLI

```shell
php bin/magento klevu:indexing:configuration-overrides-regenerate --entity-type=KLEVU_PRODUCT -vvv
```
:::

Install and recompile Magento with your new custom module.  Then (again), queue one or more products for sync by updating the product data or via CLI

```shell
php bin/magento klevu:indexing:entity-update --entity-types=KLEVU_PRODUCT --entity-ids=1,2,3 -vvv
```

and trigger a sync

```shell
php bin/magento klevu:indexing:entity-sync --entity-types=KLEVU_PRODUCT -vvv
```

### Deploy the customisation module to production

Providing everything has gone as expected, you can deploy your new module to your production environment and all future syncs will incorporate the changes.

To send updated data for your entire catalog, it is worth triggering an update via CLI

```shell
php bin/magento klevu:indexing:entity-update --entity-types=KLEVU_PRODUCT --entity-ids=all
```

You can then either trigger a sync on demand, or wait until the next scheduled process to run.

## Example Module

- [Vendor\_KlevuIndexingOverrides](https://github.com/klevultd/m2-customisations/tree/main/Vendor_KlevuIndexingOverrides)

## Further Reading

- [Klevu Custom Attributes](https://docs.klevu.com/indexing-apis/custom-attributes) (Indexing APIs)
- [Attributes](https://docs.klevu.com/klevu-magento-v4/attributes) (Klevu Magento v4)
- [Add, Update, or Delete Indexing Attributes](https://docs.klevu.com/php-sdk/add-update-delete) (Klevu PHP SDK)
- [Managing Attributes](https://docs.klevu.com/php-sdk/managing-attributes) (Klevu PHP SDK)
- [Transformers](https://github.com/klevu/php-pipelines/tree/master/src/Transformer) (Klevu Pipelines)
- [Validators](https://github.com/klevu/php-pipelines/tree/master/src/Validator) (Klevu Pipelines)



[title] 4.4.0
[path] Klevu Module v4.x Overview/Release Notes/

## Overview

This version focuses primarily on issues relating to stock changes and entity discovery in sync, as well as providing additional diagnostic information and improvements to extensibility.

## Indexing Improvements

### Changes In Stock Status Cause Products To Be Queued For Sync&#x20;

Issues relating to stock status changes not being reflected in entity discovery - for example, where a product changed to or from being in stock - which may previously have required a Klevu entity update or discovery operation have been addressed.&#x20;

Note: there remain some scenarios which will still do not cause a product to be queued for sync, primarily revolving around configurable products using Multi Source Inventory, where the last variant moves out of stock; or edge cases where variants exist in a different website to the parent. Additional improvements will be rolled out in future versions of the 4.4.x branch

### Deferred Entity Updates

To address difficulties determining stock and status changes during database transactions, and to better support customisations to stock status logic, some discovery operations are now deferred.

This means that the indexing records will be marked as "requiring update", with the applicable status flag stored for reference.&#x20;

A cron job has been added to process records requiring update, setting the Next Action if applicable. Job code: `klevu_indexing_process_require_update_entities`; Default schedule `*/15 * * * *` (though this can be modified via the `bin/magento config:set klevu:indexing:process_require_update_entities_cron_expr [CRON_EXPR]` CLI command)

### Improved Multi Source Inventory Support

A new module has been included to provide improved compatibility with Magento MSI. Package name: `klevu/module-m2-indexing-msi`; this module is required by `klevu/module-indexing-products`, though is designed to be replaceable via composer if MSI has been removed from your installation.

This module also adds a new setting to Stores > Configuration > Klevu > Developer Settings > Indexing - Products > Append Reservations Action, which allows you to determine how we respond to reservations - for example, when a sale is made through the storefront.



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/PLl1MkdPjrRTw7IlX9gM2_image.png)

**Available Options**

- **Calculate Requires Update** : Will mark the sold item(s) as requiring update and determine whether to sync via Deferred Entity Updates (see above). This is the default.
- **Mark All For Update** : Will indiscriminately mark all items as requiring a sync, regardless of whether the change has changed the product's stock status
- **No Action** : Will not respond to reservations, requiring additional update or discovery operations to queue items. This is the pre-4.4.0 behaviour

Note: if you are experiencing high traffic through the checkout, **Calculate Requires Update** is the most processing-intensive and may cause slowdown; **Mark All For Update** is quicker, bu will cause additional load on the Klevu sync process; **No Action** has negligible impact on checkout speed but may lead to inaccurate data in Klevu's indexes.

### Improved Extensibility for Stock and Status Determination

The logic to determine whether a product is out of stock, or disabled, has been moved to two independent services, which can be plugged into; preferenced; or replaced using standard Magento development practices

**Reference**

| **Product Status** | [Interface](https://github.com/klevu/module-m2-indexing-products/blob/3.4.2/Service/Provider/ProductStatusProviderInterface.php)      | [Concretion](https://github.com/klevu/module-m2-indexing-products/blob/3.4.2/Service/Provider/ProductStatusProvider.php)      |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Stock Status**   | [Interface](https://github.com/klevu/module-m2-indexing-products/blob/3.4.2/Service/Provider/ProductStockStatusProviderInterface.php) | [Concretion](https://github.com/klevu/module-m2-indexing-products/blob/3.4.2/Service/Provider/ProductStockStatusProvider.php) |

Additionally, the native Stock Status provider now supports multiple calculation methods, configurable via **Stores > Configuration > Klevu > Developer Settings >Indexing - Products > Stock Status Calculation Method**



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/TERoPPabAyhdItGTDvNQr_image.png)

**Available Options:**

- **Stock Item** : This is the default setting to provide backwards compatibility. There are known issues relating to reservations and indexing, and this setting is no longer recommended
- **Stock Registry** : Utilises the Magento stock registry, which MSI plugs into. This is recommended setting if you encounter issues with products' stock status
- **Is Available** : References the product entity's `is_available` data property
- **Is Salable** : References the product entity's `is_salable` data property

### Consolidation of Stock Status In Discovery and Payload Generation

Prior to 4.4.0, the stock status value used for entity discovery and the value included in the sync payload may have differed due to independent calculations. It is now possible to use the provider (above)'s logic to generate the sync payload value.

To support backward compatibility, this is disabled by default and must be turned on via **Stores > Configuration > Klevu > Developer Settings > Indexing - Products > Use Provider for Stock Status Value**

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/KoQ9966xCfIVxjjqq4l0F_image.png)

**NOTE: Once enabled (and the Magento config cache flushed), you will need to regenerate the indexing pipeline overrides to ensure the changes are applied**

```bash
bin/magento klevu:indexing:configuration-overrides-regenerate --entity-type KLEVU_PRODUCT
```

## Diagnostics Improvements

### Metapackage and Library Versions in Stores > Configuration

The overal metapackage version (eg 4.4.0) and the standalone Klevu library (SDK and Pipeline) versions are now available in Stores > Configuration > Klevu > Information > Module Versions



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/9fpnGLS7K0-pJWMNbzRhu_image.png)

### Cron Execution Information in Stores > Configuration

Schedule and execution information for all Klevu cron jobs can now be found under **Stores > Configuration > Klevu > Information > Cron Information**



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/wjxzRNsLMoZq5J-_2Dck5_image.png)

### Live Product Sync Information Shown In Products Grid

In addition to the existing sync entity information found in the backend products grid under Action > Klevu Sync Info, a new section has been added to display live calculated data for the record for all integrated keys - regardless whether an indexing entity is present - and all store views using that key (if multiple stores share a key).



![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/-65hZOzK-pYA16af5MFKJ_image.png)

**Information Includes**

- **Is Discovered** : Whether an indexing entity exist for this product-parent product-api key combination
- **Is Indexable** : While the Next Sync Actions shows the is\_indexable value for the sync record, this will show the real time calculated value
- **Assigned to Website** : Whether the product is assigned to the parent website for the store code in this row
- **Product Status** : whether the product is enabled *as determined by the Status Provider&#x20;*(see above)
- **Stock Status** : whether the product is in stock *as determined by the Stock Status Provider* (see above)
- **is\_salable** : the realtime value of `$product->isSalable()`
- **is\_available** : the realtime value of `$product->isAvailable()`

### Live Product Sync Information Available via CLI

A new terminal command has been added to provide a holistic overview of an individual product (including where it exists as a variant) across all integrated websites.

This information can be viewed by running the following command via the console

```bash
bin/magento klevu:indexing:sync-information --entity-type KLEVU_PRODUCT --target-entity-id [MAGENTO_PRODUCT_ID]
```

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/7TxcH8lls6MVIt1Z8pMPe_image.png)

The output contains the same information as the products grid (above) as well as

- Relevant global configuration settings
- Information about deferred processing (see above) via the **Requires Update** and **Orig Values** lines

## Minor Bugfixes and Technical Improvements

This release also contains a number of minor bug fixes and technical improvements. See changelog below for more details.

## Changelog

- \[<font color="#15803D">FEATURE</font>] Output Klevu cron execution information in Stores > Configuration
- \[<font color="#15803D">FEATURE</font>] Add CLI Command to show indexing entity sync information
- \[<font color="#2166AE">IMPROVEMENT</font>] Implement deferred stock status processing for indexing
- \[<font color="#2166AE">IMPROVEMENT</font>] Add Stores > Configuration setting to determine indexing action following product sale
- \[<font color="#2166AE">IMPROVEMENT</font>] Add Stores > Configuration setting to allow matching stock status logic for discovery and sync payload generation
- \[<font color="#2166AE">IMPROVEMENT</font>] Add Stores > Configuration setting to define method used to determine stock status for entity discovery
- \[<font color="#2166AE">IMPROVEMENT</font>] Show metapackage and SDK package versions in Stores > Configuration
- \[<font color="#2166AE">IMPROVEMENT</font>] Output additional indexing entity sync information in backend Products grid modal
- \[<font color="#2166AE">IMPROVEMENT</font>] Hide Sync Info link in backend Products grid where no Klevu API key is integrated
- \[<font color="#2166AE">IMPROVEMENT</font>] Improve stock status support for stores utilising MultiSource Inventory
- \[<font color="#B91C1C">BUGFIX</font>] Cascade variant and child stock changes to parent product (Configurable; Grouped; and Bundle)
- \[<font color="#B91C1C">BUGFIX</font>] Resolve products not being marked for sync on stock status change \*
- \[<font color="#B91C1C">BUGFIX</font>] Resolve parent stock status not correctly considered for variant stock status in some scenarios during discovery and payload generation
- \[<font color="#B91C1C">BUGFIX</font>] Resolve missing data in DiscoveryOrchestrator result objects
- \[**TECHNICAL**] Add events to indexing record provider to support customisation
- \[**TECHNICAL**] Extract Product status determination to standalone service to support customisation
- \[**TECHNICAL**] Extract Product stock status determination to standalone service to support customisation
- \[**TECHNICAL**] Implement cache clean support on StoresProvider
- \[**TECHNICAL**] Expand Indexing Entity properties to include created and update dates
- \[**TECHNICAL**] Add batch size validation to SetIndexingEntities... actions
- \[**TECHNICAL**] Add provider for consolidation product parent IDs
- \[**TECHNICAL**] Add missing dependencies
- \[<font color="#6b7280">CHORE</font>] Miscellaneous refactoring and clean-up

[space] @klevu/core reference (/klevucore-reference)

[title] klevulistfilterstoreturn
[path] Modules/

Ƭ **KlevuListFiltersToReturn**: `Object`

### Type declaration

| Name                   | Type                                                                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ---------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`              | `boolean`                                                                                                   | Whether or not to return any filters with this query. This defaults to false so no filters are returned unless requested.                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `exclude?`             | `string`\[]                                                                                                 | This is the list of filter keys that you do not want Klevu Search to include in the response. If a filter is specified in both include and exclude lists, include will take precedence.                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `include?`             | `string`\[]                                                                                                 | This is the list of filter keys that you would like to retrieve as filters. A filter may also not be returned if there aren't enough applicable records in the result set.                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `options`              | \{ `limit?`: `number` ; `mincount?`: `number` ; `order`: [`KlevuFilterOrder`](enums/KlevuFilterOrder.md)  } | -                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `options.limit?`       | `number`                                                                                                    | Specify the maximum number of options to be included per filter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `options.mincount?`    | `number`                                                                                                    | If the parameter minCount is present with a positive number, only the options with an option count equal to or higher than the minCount are included.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `options.order`        | [`KlevuFilterOrder`](enums/KlevuFilterOrder.md)                                                             | A value of 'FREQ' will sort options based on the number of records each option has in the result set. 'INDEX' will sort the options alphabetically.                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `rangeFilterSettings?` | [`KlevuRangeFilterSettings`](docId\:qEjqx8vypdhY8n1lpOGU-)\[]                                               | When minMax is false, this setting allows you to retrieve range filters for use with numeric values such as price, so you can display bands of 0-99, 100-199, etc. or a price slider. By default all attributes submitted to Klevu are indexed as STRING attributes, which means they cannot be used as range filters. The product sale price field is the only exception to this rule, which is filtered using the key klevu\_price. If you have explicitly requested and Klevu has approved that certain attributes be indexed as numerical attributes, you can also retrieve those as range filters. |

### Defined in

[models/KlevuListFilter.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuListFilter.ts#L4)

[title] advancedfiltering
[path] Modules/

▸ **advancedFiltering**(`conditions`, `filterType?`): `KlevuFetchModifer`

Create advanced filtering to the query.

### Parameters

| Name         | Type                                                                                                                                                             | Default value | Description                                          |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------- |
| `conditions` | \{ `excludeValuesInResult?`: `boolean` ; `key`: `string` ; `singleSelect`: `boolean` ; `valueOperator`: `"INCLUDE"` \| `"EXCLUDE"` ; `values`: `string`\[]  }\[] | `undefined`   | Array of conditions to apply to the query.           |
| `filterType` | `"ALL_OF"` \| `"ANY_OF"` \| `"NONE_OF"`                                                                                                                          | `"ALL_OF"`    | How conditions should be applied. Default is ALL\_OF |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/advancedFiltering/advancedFiltering.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/advancedFiltering/advancedFiltering.ts#L12)

[title] Enumeration: KMCRecommendationLogic
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KMCRecommendationLogic

## Table of contents

### Enumeration Members

- [BoughtTogether](docId\:z3h8LSdVbCGyAsT03bdBe)
- [BoughtTogetherPDP](docId\:z3h8LSdVbCGyAsT03bdBe)
- [Custom](docId\:z3h8LSdVbCGyAsT03bdBe)
- [HandPicked](docId\:z3h8LSdVbCGyAsT03bdBe)
- [NewestArrivals](docId\:z3h8LSdVbCGyAsT03bdBe)
- [OtherAlsoViewed](docId\:z3h8LSdVbCGyAsT03bdBe)
- [RecentlyViewed](docId\:z3h8LSdVbCGyAsT03bdBe)
- [Similar](docId\:z3h8LSdVbCGyAsT03bdBe)
- [Trending](docId\:z3h8LSdVbCGyAsT03bdBe)
- [TrendingPersonalized](docId\:z3h8LSdVbCGyAsT03bdBe)
- [VisuallySimilar](docId\:z3h8LSdVbCGyAsT03bdBe)

## Enumeration Members

### BoughtTogether

• **BoughtTogether** = `"BOUGHT_TOGETHER"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:55](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L55)

***

### BoughtTogetherPDP

• **BoughtTogetherPDP** = `"BOUGHT_TOGETHER_PDP"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:56](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L56)

***

### Custom

• **Custom** = `"CUSTOM_LOGIC"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L58)

***

### HandPicked

• **HandPicked** = `"HAND_PICKED"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:52](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L52)

***

### NewestArrivals

• **NewestArrivals** = `"NEWEST_ARRIVALS"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:50](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L50)

***

### OtherAlsoViewed

• **OtherAlsoViewed** = `"OTHER_ALSO_VIEWED"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:53](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L53)

***

### RecentlyViewed

• **RecentlyViewed** = `"RECENTLY_VIEWED"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:51](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L51)

***

### Similar

• **Similar** = `"SIMILAR"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:54](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L54)

***

### Trending

• **Trending** = `"TRENDING"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:48](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L48)

***

### TrendingPersonalized

• **TrendingPersonalized** = `"TRENDING_PERSONALIZED"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:49](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L49)

***

### VisuallySimilar

• **VisuallySimilar** = `"VISUALLY_SIMILAR"`

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:57](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L57)

[title] applyfilter
[path] Modules/

Ƭ **ApplyFilter**: `Object`

### Type declaration

| Name                    | Type                                 |
| ----------------------- | ------------------------------------ |
| `key`                   | `string`                             |
| `settings?`             | \{ `singleSelect`: `boolean`  }      |
| `settings.singleSelect` | `boolean`                            |
| `values`                | `string`\[] \| \[`number`, `number`] |

### Defined in

[modifiers/applyFilter/applyFilter.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/applyFilter/applyFilter.ts#L5)

[title] Interface: KMCRootObject
[path] Interfaces/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KMCRootObject

## Table of contents

### Properties

- [klevuLayoutVersion](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_abTestActive](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_addToCartEnabled](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_apiDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_categorySearchEnabled](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_cmsAnalyticsDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_cmsApiKey](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_cmsEnabled](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_cmsSearchDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_filtersEnabled](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_filtersOnLeft](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_fluidLayoutEnabled](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_isSearchActive](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_layoutType](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_layoutView](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_loadMapFile](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_logoFreeSearch](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_lookForDataInSameFeed](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_multiSelectFilters](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_popularProductsOfSite](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_productsToShowInSlimLayout](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showBannerAds](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showOutOfStock](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showPopularSearches](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showPopuralTerms](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showPriceSlider](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showPrices](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showProductCode](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_showRecentSerches](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_uc\_userOptions](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_userAnalyticsDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_userJavascriptDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_userSearchDomain](docId\:cmyvmblfFvreTWOW6tgAd)
- [klevu\_webstorePopularTerms](docId\:cmyvmblfFvreTWOW6tgAd)

## Properties

### klevuLayoutVersion

• **klevuLayoutVersion**: `string`



not in use , used by jsv1 for loading version of layout , could
not be expanded in kmc to support jsv2 theme versions

### Defined in

[models/KMCRoot.ts:107](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L107)

***

### klevu\_abTestActive

• **klevu\_abTestActive**: `boolean`

Is A/B test active

### Defined in

[models/KMCRoot.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L5)

***

### klevu\_addToCartEnabled

• **klevu\_addToCartEnabled**: `boolean`

activates the display of add to cart button

### Defined in

[models/KMCRoot.ts:53](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L53)

***

### klevu\_apiDomain

• **klevu\_apiDomain**: `string`

used by ab test to define the domain of the api, in plan to move all apis
to the same domain

### Defined in

[models/KMCRoot.ts:77](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L77)

***

### klevu\_categorySearchEnabled

• **klevu\_categorySearchEnabled**: `boolean`



not in use , enable category search

### Defined in

[models/KMCRoot.ts:125](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L125)

***

### klevu\_cmsAnalyticsDomain

• **klevu\_cmsAnalyticsDomain**: `string`

Domain to send cms analytics to

### Defined in

[models/KMCRoot.ts:21](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L21)

***

### klevu\_cmsApiKey

• **klevu\_cmsApiKey**: `string`



not in use, originally used for different api key for cms
content

### Defined in

[models/KMCRoot.ts:121](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L121)

***

### klevu\_cmsEnabled

• **klevu\_cmsEnabled**: `boolean`

activates the tab cms content

### Defined in

[models/KMCRoot.ts:62](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L62)

***

### klevu\_cmsSearchDomain

• **klevu\_cmsSearchDomain**: `string`



not in use , similar to klevu\_userAnalyticsDomain

### Defined in

[models/KMCRoot.ts:98](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L98)

***

### klevu\_filtersEnabled

• **klevu\_filtersEnabled**: `boolean`

used to activate the filters

### Defined in

[models/KMCRoot.ts:86](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L86)

***

### klevu\_filtersOnLeft

• **klevu\_filtersOnLeft**: `boolean`

activates the filters on the left for quick grid view layout, defaults to
true

### Defined in

[models/KMCRoot.ts:67](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L67)

***

### klevu\_fluidLayoutEnabled

• **klevu\_fluidLayoutEnabled**: `boolean`



not in use , used by jsv1 to enable extra file loading

### Defined in

[models/KMCRoot.ts:94](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L94)

***

### klevu\_isSearchActive

• **klevu\_isSearchActive**: `boolean`



not in use , used by jsv1 to load extra files

### Defined in

[models/KMCRoot.ts:90](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L90)

***

### klevu\_layoutType

• **klevu\_layoutType**: `string`



quick search layout type, basic or slim, defaults to basic

### Defined in

[models/KMCRoot.ts:116](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L116)

***

### klevu\_layoutView

• **klevu\_layoutView**: `string`

used to switch between grid or list view of the quick basic view

### Defined in

[models/KMCRoot.ts:34](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L34)

***

### klevu\_loadMapFile

• **klevu\_loadMapFile**: `boolean`



not in use , used by jsv1 to know if the url map file should be
loaded

### Defined in

[models/KMCRoot.ts:112](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L112)

***

### klevu\_logoFreeSearch

• **klevu\_logoFreeSearch**: `boolean`



not in use, during trial used to have klevu watermark, no
longer a option so not used

### Defined in

[models/KMCRoot.ts:147](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L147)

***

### klevu\_lookForDataInSameFeed

• **klevu\_lookForDataInSameFeed**: `boolean`



unknown

### Defined in

[models/KMCRoot.ts:102](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L102)

***

### klevu\_multiSelectFilters

• **klevu\_multiSelectFilters**: `boolean`

### Defined in

[models/KMCRoot.ts:133](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L133)

***

### klevu\_popularProductsOfSite

• **klevu\_popularProductsOfSite**: `KlevuPopularProductsOfSite`\[]

Most popular products of the store

### Defined in

[models/KMCRoot.ts:17](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L17)

***

### klevu\_productsToShowInSlimLayout

• **klevu\_productsToShowInSlimLayout**: `string`

the limit for the query of products and category for the slim quick view
design(cms is hardcoded to 3)

### Defined in

[models/KMCRoot.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L58)

***

### klevu\_showBannerAds

• **klevu\_showBannerAds**: `boolean`



not in use, used to control if banner are displayed or not,
currently control via the return of banner list

### Defined in

[models/KMCRoot.ts:131](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L131)

***

### klevu\_showOutOfStock

• **klevu\_showOutOfStock**: `boolean`



not in use, as its controlled from search BE

### Defined in

[models/KMCRoot.ts:142](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L142)

***

### klevu\_showPopularSearches

• **klevu\_showPopularSearches**: `boolean`

activates popular products section of quicksearch (documented under the
popular-searches theme component)

### Defined in

[models/KMCRoot.ts:44](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L44)

***

### klevu\_showPopuralTerms

• **klevu\_showPopuralTerms**: `boolean`



not in use , because of no results redesign, it was to show the
popular terms in the no results pannel.

### Defined in

[models/KMCRoot.ts:152](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L152)

***

### klevu\_showPriceSlider

• **klevu\_showPriceSlider**: `boolean`

activates the price slider

### Defined in

[models/KMCRoot.ts:49](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L49)

***

### klevu\_showPrices

• **klevu\_showPrices**: `boolean`

activates the display of price filter and price block in product card

### Defined in

[models/KMCRoot.ts:71](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L71)

***

### klevu\_showProductCode

• **klevu\_showProductCode**: `boolean`

used for displaying product sku in the product cards as part of the name

### Defined in

[models/KMCRoot.ts:39](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L39)

***

### klevu\_showRecentSerches

• **klevu\_showRecentSerches**: `boolean`

activates recent search's section of quick (documented under the
recent-searches theme component)

### Defined in

[models/KMCRoot.ts:82](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L82)

***

### klevu\_uc\_userOptions

• **klevu\_uc\_userOptions**: `KlevuUcUserOptions`

Messages and banners created by user in KMC

### Defined in

[models/KMCRoot.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L9)

***

### klevu\_userAnalyticsDomain

• **klevu\_userAnalyticsDomain**: `string`



not in use, controlled the domain of the analytics calls , not
in use as analytics live now under same doamin

### Defined in

[models/KMCRoot.ts:138](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L138)

***

### klevu\_userJavascriptDomain

• **klevu\_userJavascriptDomain**: `string`

Domain where JSv2 is hosted on

### Defined in

[models/KMCRoot.ts:29](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L29)

***

### klevu\_userSearchDomain

• **klevu\_userSearchDomain**: `string`

Domain to send search analytics to

### Defined in

[models/KMCRoot.ts:25](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L25)

***

### klevu\_webstorePopularTerms

• **klevu\_webstorePopularTerms**: `string`\[]

Popular terms in the store

### Defined in

[models/KMCRoot.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCRoot.ts#L13)

[title] Enumeration: KlevuTypeOfSearch
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuTypeOfSearch

## Table of contents

### Enumeration Members

- [And](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [Default](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [FuzzyAnd](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [FuzzyOr](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [Or](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [WildcardAnd](docId:3FsfdwGnKdoXmw8Q6AiU3)
- [WildcardOr](docId:3FsfdwGnKdoXmw8Q6AiU3)

## Enumeration Members

### And

• **And** = `"AND"`

All of the exact words of a query must be found in a record for it to be
included in the results. No fuzziness or wildcards are included.

For example a search for "hooded jacket" will only return records which
contain the exact terms "hooded" AND "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:64](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L64)

***

### Default

• **Default** = `"DEFAULT"`

When this value is specified, Klevu will go through a number of attempts to
find matching records. The first type attempted is WILDCARD\_AND. If there
aren't any results found, Klevu tries to find products with the FUZZY\_AND
query type.

As long as no matches are found, Klevu will continue to fire different query
types in the following order:

WILDCARD\_AND
FUZZY\_AND
WILDCARD\_OR
FUZZY\_OR
Note that when a search term only contains a single word, or more than six
words, the 'OR' query types will be skipped.

### Defined in

[models/KlevuTypeOfSearch.ts:18](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L18)

***

### FuzzyAnd

• **FuzzyAnd** = `"FUZZY_AND"`

This is the same as a WILDCARD\_AND query, however a certain amount of
'fuzziness' is allowed to account for spelling mistakes.

For example, if the searched query contains spelling mistakes like "hooder
jakcet", Klevu will still be able to match any records containing the words
"hooded" AND "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:37](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L37)

***

### FuzzyOr

• **FuzzyOr** = `"FUZZY_OR"`

This is the same as a WILDCARD\_OR query, however a certain amount of
'fuzziness' is allowed to account for spelling mistakes.

For example, if the searched query contains spelling mistakes like "hooder
jakcet", Klevu will still be able to match any records containing the words
"hooded" OR "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:56](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L56)

***

### Or

• **Or** = `"OR"`

At least one exact word of a query must be found in a record for it to be
included in a results. No fuzziness or wildcards are included.

For example a search for "hooded jacket" will only return records which
contain one of the exact terms "hooded" OR "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:72](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L72)

***

### WildcardAnd

• **WildcardAnd** = `"WILDCARD_AND"`

This is an 'AND' query so all words of the query must be found somewhere in a
record for it to be included in the results. The last word of the query will
have a wildcard suffix appended.

For example, if the searched query is "hooded jacket", this will become
"hooded jacket\*", ie. Klevu will try to find records containing the word
"hooded" AND any words beginning with "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:28](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L28)

***

### WildcardOr

• **WildcardOr** = `"WILDCARD_OR"`

This is an 'OR' query so at least one of the words in the query must be found
somewhere in a record for it to be included in the results. The last word of
the query will have a wildcard suffix appended.

For example, if the searched query is "hooded jacket", this will become
"hooded jacket\*", ie. Klevu will try to find records containing the word
"hooded" OR any words beginning with "jacket".

### Defined in

[models/KlevuTypeOfSearch.ts:47](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfSearch.ts#L47)

[title] Enumeration: KlevuFilterOrder
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuFilterOrder

## Table of contents

### Enumeration Members

- [Frequency](docId\:u25KG78OsvzaBbN999cTI)
- [Index](docId\:u25KG78OsvzaBbN999cTI)

## Enumeration Members

### Frequency

• **Frequency** = `"FREQ"`

Sort options based on the number of records each option has in the result
set.

### Defined in

[models/KlevuFilterOrder.ts:6](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFilterOrder.ts#L6)

***

### Index

• **Index** = `"INDEX"`

'INDEX' will sort the options alphabetically.

### Defined in

[models/KlevuFilterOrder.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFilterOrder.ts#L10)

[title] klevuapirawresponse
[path] Modules/

Ƭ **KlevuApiRawResponse**: `Object`

Raw response from Klevu API

### Type declaration

| Name                 | Type                                                                 |
| -------------------- | -------------------------------------------------------------------- |
| `meta`               | \{ `error?`: `any` ; `qTime`: `number` ; `responseCode`: `number`  } |
| `meta.error?`        | `any`                                                                |
| `meta.qTime`         | `number`                                                             |
| `meta.responseCode`  | `number`                                                             |
| `queryResults?`      | [`KlevuQueryResult`](docId\:CGLzKe0jhD8maf-Iy_RLX)\[]                |
| `suggestionResults?` | [`KlevuSuggestionResult`](docId\:yQSz4WXRMGv61HqrbSwwi)\[]           |

### Defined in

[models/KlevuApiRawResponse.ts:185](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L185)

[title] klevunextfunc
[path] Modules/

Ƭ **KlevuNextFunc**: (`override?`: \{ `filterManager?`: [`FilterManager`](classes/FilterManager.md) ; `limit?`: `number` ; `pageIndex?`: `number`  }) => `Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

### Type declaration

▸ (`override?`): `Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

Next function is available if there are more results in the given query.
It is optimized function that removes parts from query that might slow down
the response and they are not needed after first request.

### Parameters

| Name                      | Type                                        | Description                                                                                              |
| ------------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `override?`               | `Object`                                    | -                                                                                                        |
| `override.filterManager?` | [`FilterManager`](classes/FilterManager.md) | Filter manager to apply for next function                                                                |
| `override.limit?`         | `number`                                    | Limit number of results for next query. By default this is automatically calculated from previous result |
| `override.pageIndex?`     | `number`                                    | Use page index to load certain page instead of next available. 0 is first page                           |

### Returns

`Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

### Defined in

[models/KlevuFetchResponse.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFetchResponse.ts#L16)

[title] kmcrecommendation
[path] Modules/

▸ **kmcRecommendation**(`recommendationId`, `options?`, `...modifiers`): `Promise`\<[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)>

Fetches products based on KMC recommendation. Provide id created in KMC

### Parameters

| Name               | Type                                                                       | Description                         |
| ------------------ | -------------------------------------------------------------------------- | ----------------------------------- |
| `recommendationId` | `string`                                                                   | Id of recommendation in the backend |
| `options?`         | `Partial`\<[`KlevuKMCRecommendationOptions`](docId:-_5sVna_LGb9MuD61lV08)> | -                                   |
| `...modifiers`     | `KlevuFetchModifer`\[]                                                     | -                                   |

### Returns

`Promise`\<[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)>

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:140](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L140)

[title] klevulistendomevent
[path] Modules/

▸ **KlevuListenDomEvent**(`klevuDomEvent`, `callback`): () => `void`

Helper function to listen Klevu Dom events



```ts
import { KlevuDomEvents, KlevuListenDomEvent } from '@klevu/core'

// Event to listen
const stopListen = KlevuListenDomEvent(KlevuDomEvents.LastSearchUpdate, (event) => {
  console.log('last search updated!', event.detail)
})

// stop listening
stopListen();
```

### Parameters

| Name            | Type                                        | Description                    |
| --------------- | ------------------------------------------- | ------------------------------ |
| `klevuDomEvent` | [`KlevuDomEvents`](enums/KlevuDomEvents.md) | What event to listen           |
| `callback`      | (`event`: `Event`) => `void`                | What to do when event is fired |

### Returns

`fn`

Function to stop listening

▸ (): `void`

### Returns

`void`

### Defined in

[events/KlevuDomEvents.ts:47](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuDomEvents.ts#L47)

[title] Class: MoiSession
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / MoiSession

## Table of contents

### Constructors

- [constructor](docId\:VI7zz0Y-gAkL5higBbVZ3)

### Properties

- [config](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [context](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [feedbacks](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [genericOptions](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [menu](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [messages](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [options](docId\:VI7zz0Y-gAkL5higBbVZ3)

### Methods

- [addFeedback](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [clear](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [query](docId\:VI7zz0Y-gAkL5higBbVZ3)
- [save](docId\:VI7zz0Y-gAkL5higBbVZ3)

## Constructors

### constructor

• **new MoiSession**(`state`, `options`, `context`, `config`)

### Parameters

| Name                   | Type                                                                                                                                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `state`                | `Object`                                                                                                                                                                                                      |
| `state.feedbacks`      | [`MoiSavedFeedback`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]                                                                                                                                                          |
| `state.genericOptions` | `undefined` \| \{ `options`: \{ `chat`: `string` ; `name`: `string` ; `type`: `"message"` \| `"clearChat"`  }\[]  }                                                                                           |
| `state.menu`           | `undefined` \| \{ `options`: \{ `chat`: `string` ; `name`: `string` ; `options`: \{ `key`: `string` ; `validations`: `string` ; `value`: `string`  }\[] ; `type`: `"message"` \| `"customerSupport"`  }\[]  } |
| `state.messages`       | [`MoiMessages`](docId:7vdpEs-8-0Tv_43dyA7ly)                                                                                                                                                                  |
| `options`              | [`MoiStartOptions`](docId:7vdpEs-8-0Tv_43dyA7ly)                                                                                                                                                              |
| `context`              | [`MoiContext`](docId:7vdpEs-8-0Tv_43dyA7ly)                                                                                                                                                                   |
| `config`               | [`KlevuConfig`](docId\:w2RkeCQV7dYsnPOEOFH1J)                                                                                                                                                                 |

### Defined in

[connection/moi/moi.ts:322](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L322)

## Properties

### config

• **config**: [`KlevuConfig`](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Defined in

[connection/moi/moi.ts:354](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L354)

***

### context

• **context**: [`MoiContext`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/moi/moi.ts:353](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L353)

***

### feedbacks

• **feedbacks**: [`MoiSavedFeedback`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[connection/moi/moi.ts:351](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L351)

***

### genericOptions

• `Optional` **genericOptions**: `Object`

### Type declaration

| Name      | Type                                                                                |
| --------- | ----------------------------------------------------------------------------------- |
| `options` | \{ `chat`: `string` ; `name`: `string` ; `type`: `"message"` \| `"clearChat"`  }\[] |

### Defined in

[connection/moi/moi.ts:350](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L350)

***

### menu

• **menu**: `undefined` | \{ `options`: \{ `chat`: `string` ; `name`: `string` ; `options`: \{ `key`: `string` ; `validations`: `string` ; `value`: `string`  }\[] ; `type`: `"message"` | `"customerSupport"`  }\[]  }

### Defined in

[connection/moi/moi.ts:349](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L349)

***

### messages

• **messages**: [`MoiMessages`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/moi/moi.ts:348](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L348)

***

### options

• **options**: [`MoiStartOptions`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/moi/moi.ts:352](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L352)

## Methods

### addFeedback

▸ **addFeedback**(`messageId`, `thumbs`, `reason?`): `Promise`\<[`MoiResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Parameters

| Name        | Type               |
| ----------- | ------------------ |
| `messageId` | `string`           |
| `thumbs`    | `"up"` \| `"down"` |
| `reason?`   | `string`           |

### Returns

`Promise`\<[`MoiResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Defined in

[connection/moi/moi.ts:456](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L456)

***

### clear

▸ **clear**(): `void`

### Returns

`void`

### Defined in

[connection/moi/moi.ts:417](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L417)

***

### query

▸ **query**(`request`, `target?`): `Promise`\<[`MoiResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Parameters

| Name      | Type                                                              |
| --------- | ----------------------------------------------------------------- |
| `request` | `Omit`\<[`MoiRequest`](docId:7vdpEs-8-0Tv_43dyA7ly), `"context"`> |
| `target?` | `MoiAPITarget`                                                    |

### Returns

`Promise`\<[`MoiResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Defined in

[connection/moi/moi.ts:356](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L356)

***

### save

▸ **save**(): `void`

### Returns

`void`

### Defined in

[connection/moi/moi.ts:423](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L423)

[title] klevufetchcache
[path] Modules/

• `Const` **klevuFetchCache**: `KlevuFetchCache`\<[`KlevuPayload`](docId\:FOJRevUwsN8FXfFxi3aHF), [`KlevuApiRawResponse`](docId\:OuLSbkYPK2-rGgqH6qeog)>

### Defined in

[connection/klevuFetch.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/klevuFetch.ts#L16)

## KlevuFetch Functions

### KlevuFetch

▸ **KlevuFetch**(`...functionPromises`): `Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

Function that makes query to KlevuBackend. It can take amount of queries.

### Parameters

| Name                  | Type                                                |
| --------------------- | --------------------------------------------------- |
| `...functionPromises` | [`KlevuFetchQueries`](docId\:q5OZXYWoRdA58lqyW-VbL) |

### Returns

`Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

Tools to operate results and get next results [KlevuFetchResponse](docId\:VI5JRTKTZCm6Sdx7F7IGq)

### Defined in

[connection/klevuFetch.ts:28](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/klevuFetch.ts#L28)

[title] klevuqueryresult
[path] Modules/

Ƭ **KlevuQueryResult**: `Object`

Raw query object from api

### Type declaration

| Name                            | Type                                                                                                                                                                                                                                                                                                                                                                                             | Description                                                                                                                                                                                                 |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filters?`                      | ([`KlevuFilterResultOptions`](docId\:FNVkZmp1dfTp_h3p4eBVz) \| [`KlevuFilterResultSlider`](docId\:zKpvQRhNOp9EevKLWczEn) \| [`KlevuFilterResultRating`](docId\:SHCU6ypFRKJloKIC1ArIw))\[]                                                                                                                                                                                                        | Currently available filters                                                                                                                                                                                 |
| `id`                            | `string`                                                                                                                                                                                                                                                                                                                                                                                         | Id used when defining query                                                                                                                                                                                 |
| `meta`                          | \{ `apiKey`: `string` ; `debuggingInformation`: `unknown` ; `isPersonalised`: `boolean` ; `klevuImageData?`: \{ `processed`: \{ `urls`: `string`\[]  }\[]  } ; `noOfResults`: `number` ; `notificationCode`: `number` ; `offset`: `number` ; `qTime`: `number` ; `searchedTerm`: `string` ; `totalResultsFound`: `number` ; `typeOfSearch`: [`KlevuTypeOfSearch`](enums/KlevuTypeOfSearch.md)  } | -                                                                                                                                                                                                           |
| `meta.apiKey`                   | `string`                                                                                                                                                                                                                                                                                                                                                                                         | Klevu API key                                                                                                                                                                                               |
| `meta.debuggingInformation`     | `unknown`                                                                                                                                                                                                                                                                                                                                                                                        | Information that can be useful for debugging the query. For example, the actual query that was fired by the Klevu Search engine, inclusive of any synonyms or de-compounded words taken into consideration. |
| `meta.isPersonalised`           | `boolean`                                                                                                                                                                                                                                                                                                                                                                                        | -                                                                                                                                                                                                           |
| `meta.klevuImageData?`          | \{ `processed`: \{ `urls`: `string`\[]  }\[]  }                                                                                                                                                                                                                                                                                                                                                  | The urls processed in case of image search                                                                                                                                                                  |
| `meta.klevuImageData.processed` | \{ `urls`: `string`\[]  }\[]                                                                                                                                                                                                                                                                                                                                                                     | -                                                                                                                                                                                                           |
| `meta.noOfResults`              | `number`                                                                                                                                                                                                                                                                                                                                                                                         | The number of results requested to be returned for this query.                                                                                                                                              |
| `meta.notificationCode`         | `number`                                                                                                                                                                                                                                                                                                                                                                                         | This may be populated with a code if any actions were taken on the record. Possible values are: 1: Nothing to report. 2: The price of the record is using the base currency.                                |
| `meta.offset`                   | `number`                                                                                                                                                                                                                                                                                                                                                                                         | The index of the first result returned in this response.                                                                                                                                                    |
| `meta.qTime`                    | `number`                                                                                                                                                                                                                                                                                                                                                                                         | The time taken by the Klevu Search engine to fetch the response.                                                                                                                                            |
| `meta.searchedTerm`             | `string`                                                                                                                                                                                                                                                                                                                                                                                         | The search term submitted for this query.                                                                                                                                                                   |
| `meta.totalResultsFound`        | `number`                                                                                                                                                                                                                                                                                                                                                                                         | The total number of results found for this query.                                                                                                                                                           |
| `meta.typeOfSearch`             | [`KlevuTypeOfSearch`](enums/KlevuTypeOfSearch.md)                                                                                                                                                                                                                                                                                                                                                | The query type that was executed by Klevu to retrieve the results.                                                                                                                                          |
| `records`                       | \{ `id`: `string`  } & [`KlevuRecord`](docId\:vA8Kz9WZX3r_nThlqQ1i4)\[]                                                                                                                                                                                                                                                                                                                          | -                                                                                                                                                                                                           |

### Defined in

[models/KlevuApiRawResponse.ts:110](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L110)

[title] klevuannotations
[path] Modules/

Ƭ **KlevuAnnotations**: `Object`

Fetch query results

### Type declaration

| Name                    | Type                                                   | Description                              |
| ----------------------- | ------------------------------------------------------ | ---------------------------------------- |
| `annotations?`          | \{ `fullTerm?`: `string` ; `subjects?`: `string`\[]  } | Object containing the processed data     |
| `annotations.fullTerm?` | `string`                                               | Full term extracted from query           |
| `annotations.subjects?` | `string`\[]                                            | Subjects extracted from query            |
| `apiKey?`               | `string`                                               | Api key that was used                    |
| `qTime?`                | `number`                                               | Query time for error processing          |
| `responseMessage?`      | `string`                                               | Response Message to for error processing |

### Defined in

[models/KlevuFetchResponse.ts:63](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFetchResponse.ts#L63)

[title] klevubasequery
[path] Modules/

Ƭ **KlevuBaseQuery**: `Object`

Generic

### Type declaration

| Name               | Type                                                                                                                                                                                                               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `abTestId?`        | `string`                                                                                                                                                                                                           | The unique identifier of the A/B Test.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `abTestVariantId?` | `string`                                                                                                                                                                                                           | The unique identifier of the A/B Test Variant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `boost?`           | \{ `filters?`: \{ `key`: `string` ; `values`: `string`\[] ; `weight`: `number`  }\[] ; `keywords?`: \{ `phrase`: `string` ; `weight`: `number`  }\[] ; `records?`: \{ `id`: `string` ; `weight`: `number`  }\[]  } | If you have already built up a profile of your customer and would like to use what you know about them to promote certain results, you can use the boost object within each record query. There are three ways the records can be boosted: filter conditions keywords or phrases IDs of specific records For example let's say you have an online store with an area where customers can log in. From your stores purchase history, you know that one customer is particularly interested in the brand 'KKE'. From your analytics data, you also know the same customer also looked at the product detail page of the product with ID: '31366487375934' many times. Finally, you have an area where customers can specify keywords of their interests, and this customer wrote 'comfortable'. As a merchant with all of this information available, you can build up a profile about this customer. The sample to the right shows how you would convey this information to Klevu during a search. To find out more about how boosting works with your existing merchandising rules, please read this article on How [Personalisation Works](https://help.klevu.com/support/solutions/articles/5000871357-how-does-it-work-). |
| `boost.filters?`   | \{ `key`: `string` ; `values`: `string`\[] ; `weight`: `number`  }\[]                                                                                                                                              | Specify filter values to apply a boosting score to. They key is the unique identifier of the attribute, eg. Color. Each of the values represents the value of that filter to boost, eg. red or blue.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `boost.keywords?`  | \{ `phrase`: `string` ; `weight`: `number`  }\[]                                                                                                                                                                   | Specify keywords or phrases to apply a boosting score to, for example "comfortable".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `boost.records?`   | \{ `id`: `string` ; `weight`: `number`  }\[]                                                                                                                                                                       | Specify the Klevu ID of any records to apply a boosting score to.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `filters?`         | [`KlevuListFilter`](docId:2o3vpdB6dnUslrPgAIaCs) & [`KlevuApplyFilter`](docId:18mjL60ULCGi9EQEYq1In)                                                                                                               | Apply certain filters to query. Recommended to use modifier functions for these.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `id`               | `string`                                                                                                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `isFallbackQuery?` | `boolean`                                                                                                                                                                                                          | Specify a value of true for any queries that should not be executed until some particular criteria are met, in another query. It is not possible for a fallback query to have its own fallback query. Use fallback() modifier to simplify usage                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `settings?`        | [`KlevuBaseQuerySettings`](docId\:DyD-sdD9prRQ0gcOerUbZ)                                                                                                                                                           | There are numerous settings, preferences and configurations available with APIv2 to fine-tune your search and category merchandising queries. This section explores them in more detail.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `typeOfRequest`    | [`KlevuTypeOfRequest`](enums/KlevuTypeOfRequest.md)                                                                                                                                                                | This parameter defines the type of request it is                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

### Defined in

[models/KlevuBaseQuery.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuBaseQuery.ts#L11)

[title] boughttogether
[path] Modules/

▸ **boughtTogether**(`productIdsInCart`, `options`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Bought together recommendation on checkout page

### Parameters

| Name               | Type                   |
| ------------------ | ---------------------- |
| `productIdsInCart` | `string`\[]            |
| `options`          | `Partial`\<`Options`>  |
| `...modifiers`     | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/boughtTogether/boughtTogether.ts:23](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/boughtTogether/boughtTogether.ts#L23)

[title] fallback
[path] Modules/

▸ **fallback**(`func`, `options?`): `KlevuFetchModifer`

If original query doesn't return enough results then fallback query is run added to results

### Parameters

| Name       | Type                                                            |
| ---------- | --------------------------------------------------------------- |
| `func`     | [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito) |
| `options?` | [`KlevuFallbackQueryOptions`](docId:-fi6i8IwD3C5-UZbn4THv)      |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/fallback/fallback.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/fallback/fallback.ts#L16)

[title] klevubasequerysettings
[path] Modules/

Ƭ **KlevuBaseQuerySettings**: `Object`

### Type declaration

| Name                                    | Type                                                                                                                                                                                                                                                                                                                                              | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `advancedSorting?`                      | \{ `key`: `string` ; `order`: [`AdvancedSortingDiretion`](enums/AdvancedSortingDiretion.md) ; `type`: `"FIELD"`  }\[]                                                                                                                                                                                                                             | If sort has been set to ADVANCED\_SORT then following object is used to define sorting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `campaignForCatNav?`                    | `string`                                                                                                                                                                                                                                                                                                                                          | In KMC the user is able to create campaigns for collections; which are specific rules that are tied to a start and end date. This allows a user to create rules that assist in promoting or demoting products during a sale, event, season, etc. This parameter allows a user to pass in the ID of a campaign into a search. The implementation can be handled any way the user chooses: URL paramters, cookie, localStorage, session, DB, etc.                                                                                                                                                                                                                                                                                                                                                                                                  |
| `context?`                              | \{ `recentObjects?`: \{ `records`: \{ `id`: `string`  }\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[] ; `sourceObjects?`: \{ `records`: (\{ `itemGroupId`: `string`  } \| \{ `id`: `string`  } \| \{ `url`: `string`  })\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[]  } | -                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `context.recentObjects?`                | \{ `records`: \{ `id`: `string`  }\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[]                                                                                                                                                                                                                              | @TODO: Rewrite this doc. Describe how personalisation works Use this object to specify the records (e.g. products, categories, etc.) that were recently interacted with by a customer. Please only specify one recentObject object per record type, one for all KLEVU\_PRODUCT entries, another for all KLEVU\_CMS pages visited, etc. Each recentObject object may contain multiple record objects (e.g. 5 recently viewed products). The most recently clicked record should be the first element in the array.                                                                                                                                                                                                                                                                                                                                |
| `context.sourceObjects?`                | \{ `records`: (\{ `itemGroupId`: `string`  } \| \{ `id`: `string`  } \| \{ `url`: `string`  })\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[]                                                                                                                                                                  | Used with visually similar recommendation search                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `customANDQuery?`                       | `string`                                                                                                                                                                                                                                                                                                                                          | The custom query you would like to fire, which Klevu automatically converts into an appropriate query to be included with the request. Use a - character before the parenthesis to exclude records matching the contained condition. This is advanced usage of our API and you may need some help with building these queries, so when you need support please reach out to us via the Community Forum.                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `excludeIds?`                           | \{ `key`: `string` ; `value`: `string`  }\[]                                                                                                                                                                                                                                                                                                      | Use this field to exclude certain records from the search results. You can specify a record id to control this at variant level, or an itemGroupId to control this at compound level.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `fallbackQueryId?`                      | `string`                                                                                                                                                                                                                                                                                                                                          | The ID of another query which should be fired if the current query yields too few results.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `fallbackWhenCountLessThan?`            | `number`                                                                                                                                                                                                                                                                                                                                          | Use this parameter to specify the criteria for when a fallback query will be fired. For example, if you would like a fallback query to fire when you have two results or less, specify a value of '3'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `fields?`                               | [`KlevuRecordFields`](docId:0GJGfiUirmy4bKyBKAkqe)\[]                                                                                                                                                                                                                                                                                             |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `groupBy?`                              | `"id"` \| `"name"`                                                                                                                                                                                                                                                                                                                                | The groupBy parameter takes the name of a field indexed in the Klevu Search backend and ensures that there is only one record for each unique value of this field in the search results. By default, the groupBy operation is performed on the itemGroupId field. When querying for KLEVU\_CATEGORY or KLEVU\_CMS records, it is recommended to use name as the groupBy parameter value.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `groupCondition?`                       | `KlevuGroupConditions`                                                                                                                                                                                                                                                                                                                            | The groupCondition object can be used for applying the advance filtering conditions so your customers can fine-tune their results based on relevant attributes.  Here is an example of how to use the groupCondition object. `"groupCondition": { "groupOperator": "ANY_OF", "conditions": [ { "key": "klevu_price", "valueOperator": "INCLUDE", "singleSelect": true, "excludeValuesInResult": true, "values": ["20 - 25"] }, { "key": "itemGroupId", "valueOperator": "EXCLUDE", "singleSelect": false, "values": ["4384028262462"] }, { "key": "size", "valueOperator": "EXCLUDE", "singleSelect": false, "values": ["Small", "Large"] } ] }`                                                                                                                                                                                                 |
| `includeIds?`                           | \{ `key`: `string` ; `value`: `string`  }\[]                                                                                                                                                                                                                                                                                                      | Specify any records which should be included with the results, even if the Klevu search query did not match them. You can specify a record id to control this at variant level, or a itemGroupId to control this at compound item level.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `limit?`                                | `number`                                                                                                                                                                                                                                                                                                                                          | Specify the number of record you would like to display per page.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `offset?`                               | `number`                                                                                                                                                                                                                                                                                                                                          | Specify the index at which to start counting the number of results from. The index of the first record in a result set is 0. Thus, if you want to start from the 6th result, use an offset of 5.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `personalisation?`                      | \{ `enablePersonalisation`: `true` ; `fields?`: [`KlevuRecordFields`](docId:0GJGfiUirmy4bKyBKAkqe)\[]  }                                                                                                                                                                                                                                          | When a customer enters a physical shop, they may express their preferences to an in-store assistant by highlighting the colours they like, the brands they prefer and what they have purchased before. The in-store assistant would then use this information to show the customer products they are most likely interested in first, before showing them any others that still may be suitable. Klevu A.I. is your online assistant. This personalisation can be provided in two ways: including some information about the customer's browsing history with each request defining your own boosting rules based on information you already know about the customer You can read more about how this works in our [Personalisation Guide](https://help.klevu.com/support/solutions/articles/5000871361-do-you-offer-apis-for-personalisation-). |
| `personalisation.enablePersonalisation` | `true`                                                                                                                                                                                                                                                                                                                                            | This must be set to 'true' for enabling personalisation on a particular request. If set to 'false', the recent objects within the context object will be ignored                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `personalisation.fields?`               | [`KlevuRecordFields`](docId:0GJGfiUirmy4bKyBKAkqe)\[]                                                                                                                                                                                                                                                                                             | This is an optional field. By default, Klevu will analyse all attributes of the records the customer has interacted with, in order to determine the common patterns. If you prefer to focus on particular aspects, for example brand or price, specify those attributes within this object.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `priceFieldSuffix?`                     | `string`                                                                                                                                                                                                                                                                                                                                          | If you have multiple currency support enabled for your store, this parameter can be used to retrieve prices for a specific currency. For example, if the data you have indexed with Klevu includes prices for a base currency GBP and an additional currency USD, a value of 'GBP' or 'USD' here will display the relevant currency values for your records.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `query?`                                | [`KlevuBaseQuerySettingsQuery`](docId\:h8sc81d2rTm9HYUndahZN)                                                                                                                                                                                                                                                                                     | -                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `searchPrefs?`                          | [`KlevuSearchPreference`](enums/KlevuSearchPreference.md)\[]                                                                                                                                                                                                                                                                                      | There are a number of preferences available for fine-tuning your queries. For example you can control whether or not to allow fuzzy search for spelling mistakes on a query by query basis. The available searchPrefs are detailed below.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `sort?`                                 | [`KlevuSearchSorting`](enums/KlevuSearchSorting.md)                                                                                                                                                                                                                                                                                               | The default sorting of results is RELEVANCE, which uses Klevu A.I. to determine the order. There are various other options available which you can provide to your customers as required.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `topIds?`                               | \{ `key`: `string` ; `value`: `string`  }\[]                                                                                                                                                                                                                                                                                                      | Specify any records which should always be displayed at the top of the result set. You can specify a record id to control this at variant level, or a itemGroupId to control this at compound item level. Note that this is only applicable when the sort order is by 'RELEVANCE'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `typeOfRecords?`                        | [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)\[]                                                                                                                                                                                                                                                                                         | In addition to Products, Categories and CMS Pages, Klevu APIv2 allows you to search for custom entities. For example if you want to display results for recipes, articles or physical stores within your search you can do so by utilising the typeOfRecords parameter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `typeOfSearch?`                         | [`KlevuTypeOfSearch`](enums/KlevuTypeOfSearch.md)                                                                                                                                                                                                                                                                                                 | The typeOfSearch parameter defines the behaviour when identifying matches for a searched term. For example, whether all or just one of the entered words must be matched, whether to allow spelling mistakes, etc.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `visibilityGroupID?`                    | `string`                                                                                                                                                                                                                                                                                                                                          | A common B2B requirement is different product visibility and prices based on a customer group. With Klevu APIv2 you can specify parameters to filter out products which a particular customer should not see, and also show them specific prices if they differ from the base price. When specifying a value for priceFieldSuffix, the following fields in your response data will be replaced with the value indexed with Klevu for the corresponding currency and group: price, salePrice, currency When specifying a value for visibilityGroupID, any records that do not belong to that group will be excluded from the results. In the example to the right, the same product is indexed with data for currencies 'GBP' and 'USD'. It's visibility is set to groups 'my\_group\_1' and 'my\_group\_3', but not 'my\_group\_2'.              |

### Defined in

[models/KlevuBaseQuerySettings.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuBaseQuerySettings.ts#L11)

[title] klevubasequerysettingsquery
[path] Modules/

Ƭ **KlevuBaseQuerySettingsQuery**: `Object`

### Type declaration

| Name            | Type     | Description                                                                                                                                                                                                                                                                                            |
| --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `categoryPath?` | `string` | Specify the name of the category to retrieve results from, in the same case and format as it is indexed with Klevu. For nested categories, use the ; character to separate the hierarchy. For example, for 'Mens > Shoes > Trainers and Sneakers' you would specify: Mens;Shoes;Trainers and Sneakers. |
| `term?`         | `string` | This is the phrase to be searched. It can be any free text up-to 128 characters long. If a longer string is provided it is automatically truncated after the first 128 characters.                                                                                                                     |

### Defined in

[models/KlevuBaseQuerySettingsQuery.ts:1](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuBaseQuerySettingsQuery.ts#L1)

[title] klevupackfetchresult
[path] Modules/

▸ **KlevuPackFetchResult**(`response`): [`KlevuApiRawResponse`](docId\:OuLSbkYPK2-rGgqH6qeog)

Returns only JSON from KlevuFetch that can be sent to client in SSR process to hydrate

### Parameters

| Name       | Type                                                 | Description                  |
| ---------- | ---------------------------------------------------- | ---------------------------- |
| `response` | [`KlevuFetchResponse`](docId\:VI5JRTKTZCm6Sdx7F7IGq) | Response value of KlevuFetch |

### Returns

[`KlevuApiRawResponse`](docId\:OuLSbkYPK2-rGgqH6qeog)

JSON only raw response

### Defined in

[connection/hydration.ts:14](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/hydration.ts#L14)

[title] klevugetbannersbytype
[path] Modules/

▸ **KlevuGetBannersByType**(`banners`, `searchType`, `termOrCategory`): [`KlevuBanner`](interfaces/KlevuBanner.md)\[]

### Parameters

| Name             | Type                                          |
| ---------------- | --------------------------------------------- |
| `banners`        | [`KlevuBanner`](interfaces/KlevuBanner.md)\[] |
| `searchType`     | `KlevuBannerSearchType`                       |
| `termOrCategory` | `string`                                      |

### Returns

[`KlevuBanner`](interfaces/KlevuBanner.md)\[]

### Defined in

[utils/getBannersByType.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/utils/getBannersByType.ts#L5)

[title] klevurecord
[path] Modules/

Ƭ **KlevuRecord**: `Object`

### Index signature

▪ \[key: `string`]: `any`

### Type declaration

| Name                          | Type                                                                                                                               | Description                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `brand`                       | `string`                                                                                                                           | The brand of the product, eg. 'Nike'.                                                                                                                                                                                                                                                                                                                                                                               |
| `category`                    | `string`                                                                                                                           | A double semicolon ;; separated list of the most specific categories, not including their full path. For example if a record was in 'Mens > Shoes' and 'Mens > Tees', the value would be Shoes;;Tees.                                                                                                                                                                                                               |
| `currency`                    | `string`                                                                                                                           | The currency code applicable to the price values being displayed.                                                                                                                                                                                                                                                                                                                                                   |
| `deliveryInfo`                | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `discount`                    | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `freeShipping`                | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `groupPrices`                 | `string`                                                                                                                           | This field is not always populated and is mostly used in older integrations. It includes the prices of your record in format groupId\:price so you can use your own frontend logic to display prices in realtime. If you are using the B2B group price search parameters described in this documentation, the price and salePrice are automatically calculated so there is no need to use this field in most cases. |
| `hideAddToCart`               | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `hideGroupPrices`             | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `id`                          | `string`                                                                                                                           | The unique identifier of the record within Klevu.                                                                                                                                                                                                                                                                                                                                                                   |
| `image`                       | `string`                                                                                                                           | The fully qualified URL to the main image of your record.                                                                                                                                                                                                                                                                                                                                                           |
| `imageHover`                  | `string`                                                                                                                           | The fully qualified URL to the secondary image of your record.                                                                                                                                                                                                                                                                                                                                                      |
| `imageUrl`                    | `string`                                                                                                                           | The fully qualified URL to the main image of your record.                                                                                                                                                                                                                                                                                                                                                           |
| `inStock`                     | `string`                                                                                                                           | Whether or not your record is in stock, 'yes' or 'no'.                                                                                                                                                                                                                                                                                                                                                              |
| `itemGroupId`                 | `string`                                                                                                                           | The identifier used to group compound products together, eg. the ID of the parent in the case of a configurable product.                                                                                                                                                                                                                                                                                            |
| `klevu_bulk_boosting`         | `number`                                                                                                                           | Any manual score assigned by the manual boosting rules. This value must be either explicitly requested in fields or using Search Preference enableScores.                                                                                                                                                                                                                                                           |
| `klevu_category`              | `string`                                                                                                                           | This is mostly for internal purposes, but includes the categorisation of the record within Klevu. For example KLEVU\_PRODUCT;;Shop All;;Bath;;;groupid\_1 @ku\@kuCategory\@ku\@.                                                                                                                                                                                                                                    |
| `klevu_manual_boosting`       | `number`                                                                                                                           | Any manual score assigned by the merchant. This value must be either explicitly requested in fields or using Search Preference enableScores.                                                                                                                                                                                                                                                                        |
| `klevu_selflearning_boosting` | `number`                                                                                                                           | The machine learning score assigned by the Klevu Search engine. This value must be either explicitly requested in fields or using Search Preference enableScores.                                                                                                                                                                                                                                                   |
| `name`                        | `string`                                                                                                                           | The name of your record, eg. the product name or category title.                                                                                                                                                                                                                                                                                                                                                    |
| `price`                       | `string`                                                                                                                           | The original price of your product, before any discounts. This can be used as 'was price' when used in conjunction with salePrice.                                                                                                                                                                                                                                                                                  |
| `rating`                      | `number`                                                                                                                           | The rating of your product, between 0 and 5.                                                                                                                                                                                                                                                                                                                                                                        |
| `salePrice`                   | `string`                                                                                                                           | The actual selling price of your product, or 'now' price when used in conjunction with price. Note that when using filters, the sale price is represented by klevu\_price.                                                                                                                                                                                                                                          |
| `score`                       | `number`                                                                                                                           | The score the record has achieved, ie. how relevant it is, which is used for sorting by relevance. This value must be either explicitly requested in fields or using Search Preference enableScores.                                                                                                                                                                                                                |
| `shortDesc`                   | `string`                                                                                                                           | The short description of your record.                                                                                                                                                                                                                                                                                                                                                                               |
| `sku`                         | `string`                                                                                                                           | The Stock Keeping Unit of the record.                                                                                                                                                                                                                                                                                                                                                                               |
| `startPrice`                  | `string`                                                                                                                           | The salePrice of the lowest variant within all those indexed with the same itemGroupId. This can be used if you would like to show 'as low as' price.                                                                                                                                                                                                                                                               |
| `storeBaseCurrency`           | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `swatches?`                   | \{ `color`: `string` ; `id`: `string` ; `image`: `string` ; `numberOfAdditionalVariants`: `string` ; `swatchImage`: `string`  }\[] | If your indexed data includes variants with swatch information, this will be provided here as a nested object with the following elements                                                                                                                                                                                                                                                                           |
| `swatchesInfo`                | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `tags`                        | `string`                                                                                                                           | Any tags or keywords Klevu has saved for the record.                                                                                                                                                                                                                                                                                                                                                                |
| `toPrice`                     | `string`                                                                                                                           | The salePrice of the highest variant within all those indexed with the same itemGroupId. This can be used if you would like to show 'from X to Y' price range.                                                                                                                                                                                                                                                      |
| `totalVariants`               | `number`                                                                                                                           | How many additional variants are available for this product. For example when searching for 'small tshirt', if a product has 3 colours available in small then the value here will be 2. If the search was 'tshirt' then the same record would return a value of 8 if there are 3 colours and 3 sizes of each available.                                                                                            |
| `type`                        | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `typeOfRecord`                | [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)                                                                             | The type of record, e.g. KLEVU\_PRODUCT, KLEVU\_CMS, KLEVU\_CATEGORY, etc.                                                                                                                                                                                                                                                                                                                                          |
| `url`                         | `string`                                                                                                                           | The fully qualified URL used to access the record in your store.                                                                                                                                                                                                                                                                                                                                                    |
| `variantId?`                  | `string`                                                                                                                           | The identifier used at the platform level; which could be different from the unique Klevu ID, eg. the ID of the variant in the case of a configurable product.                                                                                                                                                                                                                                                      |
| `weight`                      | `string`                                                                                                                           | -                                                                                                                                                                                                                                                                                                                                                                                                                   |

### Defined in

[models/KlevuRecord.ts:3](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuRecord.ts#L3)

[title] boostwithfiltermanager
[path] Modules/

▸ **boostWithFilterManager**(`manager`, `weights`): `KlevuFetchModifer`

Boost query with currect selection of filter manager

### Parameters

| Name      | Type                                          | Description                                                       |
| --------- | --------------------------------------------- | ----------------------------------------------------------------- |
| `manager` | [`FilterManager`](classes/FilterManager.md)   | Instance of filter manager to use for selection of current values |
| `weights` | \{ `key`: `string` ; `weight`: `number`  }\[] | Tell the weight of each filter                                    |

### Returns

`KlevuFetchModifer`

KlevuModifier that be used to modify query

### Defined in

[modifiers/boostWithFilterManager/boostWithFilterManager.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/boostWithFilterManager/boostWithFilterManager.ts#L13)

[title] Interfaces
[path] /

File not found!

[title] klevurangefiltersettings
[path] Modules/

Ƭ **KlevuRangeFilterSettings**: `Object`

### Type declaration

| Name             | Type      | Description                                                                                                                                                                |
| ---------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`            | `string`  | This is the identifier of your numerical attribute, eg. 'klevu\_price'.                                                                                                    |
| `minMax`         | `boolean` | If set to true, the Klevu Search engine calculates the minimum and maximum values for this filter for use with a slider.                                                   |
| `rangeInterval?` | `number`  | If a positive value is provided, the Klevu Search engine will calculate ranges for this value. For example a value of 100 would give ranges from 0 to 99, 100 to 299, etc. |

### Defined in

[models/KlevuRangeFilterSettings.ts:1](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuRangeFilterSettings.ts#L1)

[title] Enumeration: KlevuFilterType
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuFilterType

Filter types Klevu support

## Table of contents

### Enumeration Members

- [Options](docId\:WW8-Ksa2-cuoaIcKix5tp)
- [Rating](docId\:WW8-Ksa2-cuoaIcKix5tp)
- [Slider](docId\:WW8-Ksa2-cuoaIcKix5tp)

## Enumeration Members

### Options

• **Options** = `"OPTIONS"`

### Defined in

[models/KlevuApiRawResponse.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L8)

***

### Rating

• **Rating** = `"RATING"`

### Defined in

[models/KlevuApiRawResponse.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L10)

***

### Slider

• **Slider** = `"SLIDER"`

### Defined in

[models/KlevuApiRawResponse.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L9)

[title] filtermanagerfilters
[path] Modules/

Ƭ **FilterManagerFilters**: [`KlevuFilterResultOptions`](docId\:FNVkZmp1dfTp_h3p4eBVz) | [`KlevuFilterResultSlider`](docId\:zKpvQRhNOp9EevKLWczEn) | [`KlevuFilterResultRating`](docId\:SHCU6ypFRKJloKIC1ArIw)

### Defined in

[store/filterManager.ts:15](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L15)

[title] Classes
[path] /

File not found!

[title] categorymerchandising
[path] Modules/

▸ **categoryMerchandising**(`category`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Fetch products for a category listing page.
Default result id is "categoryMerchandising".

### Parameters

| Name           | Type                                                                    |
| -------------- | ----------------------------------------------------------------------- |
| `category`     | `undefined` \| `string`                                                 |
| `options?`     | `Partial`\<[`KlevuMerchandisingOptions`](docId\:Wa_CuGIog7wxiYPZYOrgu)> |
| `...modifiers` | `KlevuFetchModifer`\[]                                                  |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/categoryMerchandising/categoryMerchandising.ts:30](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/categoryMerchandising/categoryMerchandising.ts#L30)

[title] moichatmodes
[path] Modules/

Ƭ **MoiChatModes**: `"PQA"`

### Defined in

[connection/moi/moi.ts:160](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L160)

[title] Enumeration: KlevuSearchSorting
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuSearchSorting

## Table of contents

### Enumeration Members

- [AdvancedSorting](docId\:RX8X6NC9hFqbDTOXiITMz)
- [NameAsc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [NameDesc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [NewArrivalAsc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [NewArrivalDesc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [PriceAsc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [PriceDesc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [RatingAsc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [RatingDesc](docId\:RX8X6NC9hFqbDTOXiITMz)
- [Relevance](docId\:RX8X6NC9hFqbDTOXiITMz)

## Enumeration Members

### AdvancedSorting

• **AdvancedSorting** = `"ADVANCED_SORT"`

Advanced sorting method that requires list of keys to be sorted with. Recommended use `advancedSorting()` modifier instead of specifying this

### Defined in

[models/KlevuSearchSorting.ts:49](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L49)

***

### NameAsc

• **NameAsc** = `"NAME_ASC"`

Sort the results by the name of each record, in alphabetical order.

### Defined in

[models/KlevuSearchSorting.ts:20](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L20)

***

### NameDesc

• **NameDesc** = `"NAME_DESC"`

Sort the results by the name of each record, in alphabetical order.

### Defined in

[models/KlevuSearchSorting.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L24)

***

### NewArrivalAsc

• **NewArrivalAsc** = `"NEW_ARRIVAL_ASC"`

Sort your records based on their published date. Please see support article
for important information about sorting by newness.

### Defined in

[models/KlevuSearchSorting.ts:39](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L39)

***

### NewArrivalDesc

• **NewArrivalDesc** = `"NEW_ARRIVAL_DESC"`

Sort your records based on their published date. Please see support article
for important information about sorting by newness.

### Defined in

[models/KlevuSearchSorting.ts:44](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L44)

***

### PriceAsc

• **PriceAsc** = `"PRICE_ASC"`

Sort the results by the salePrice value of each record.

### Defined in

[models/KlevuSearchSorting.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L12)

***

### PriceDesc

• **PriceDesc** = `"PRICE_DESC"`

Sort the results by the salePrice value of each record.

### Defined in

[models/KlevuSearchSorting.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L16)

***

### RatingAsc

• **RatingAsc** = `"RATING_ASC"`

Sort the results by each record's average rating, if this data has been
indexed in your store.

### Defined in

[models/KlevuSearchSorting.ts:29](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L29)

***

### RatingDesc

• **RatingDesc** = `"RATING_DESC"`

Sort the results by each record's average rating, if this data has been
indexed in your store.

### Defined in

[models/KlevuSearchSorting.ts:34](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L34)

***

### Relevance

• **Relevance** = `"RELEVANCE"`

This is the default sort order, which uses a combination of Klevu A.I. and
your own merchandising configuration to determine the order of the results.
Please read this article for more information about how Klevu ranks and
orders the results.

### Defined in

[models/KlevuSearchSorting.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchSorting.ts#L8)

[title] Enums
[path] /

File not found!

[title] klevupayload
[path] Modules/

Ƭ **KlevuPayload**: `Object`

### Type declaration

| Name              | Type                                                       |
| ----------------- | ---------------------------------------------------------- |
| `context`         | \{ `apiKeys`: `string`\[]  }                               |
| `context.apiKeys` | `string`\[]                                                |
| `recordQueries?`  | [`KlevuAllRecordQueries`](docId\:aemJGcPHnPvj5gp7OE6gs)\[] |
| `suggestions?`    | [`KlevuSuggestionQuery`](docId:1_-FvnZldotd6ffHFIrs5)\[]   |

### Defined in

[models/KlevuPayload.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuPayload.ts#L4)

[title] Class: FilterManager
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / FilterManager

Filter manager is used to store and handle filters (facets) in the results easily.
It can be easily used with applyFilterWithFilterManager() and listFilters() modifiers

## Table of contents

### Constructors

- [constructor](docId\:ztQPUeYzosySERBcqiw4h)

### Properties

- [filters](docId\:ztQPUeYzosySERBcqiw4h)

### Accessors

- [options](docId\:ztQPUeYzosySERBcqiw4h)
- [sliders](docId\:ztQPUeYzosySERBcqiw4h)

### Methods

- [clear](docId\:ztQPUeYzosySERBcqiw4h)
- [clearOptionSelections](docId\:ztQPUeYzosySERBcqiw4h)
- [currentSelection](docId\:ztQPUeYzosySERBcqiw4h)
- [deselectOption](docId\:ztQPUeYzosySERBcqiw4h)
- [getCurrentState](docId\:ztQPUeYzosySERBcqiw4h)
- [getOptionByKeyCreateIfNotExists](docId\:ztQPUeYzosySERBcqiw4h)
- [initFromListFilters](docId\:ztQPUeYzosySERBcqiw4h)
- [readFromURLParams](docId\:ztQPUeYzosySERBcqiw4h)
- [selectOption](docId\:ztQPUeYzosySERBcqiw4h)
- [selectedFilters](docId\:ztQPUeYzosySERBcqiw4h)
- [setState](docId\:ztQPUeYzosySERBcqiw4h)
- [toApplyFilters](docId\:ztQPUeYzosySERBcqiw4h)
- [toURLParams](docId\:ztQPUeYzosySERBcqiw4h)
- [toggleOption](docId\:ztQPUeYzosySERBcqiw4h)
- [updateSlide](docId\:ztQPUeYzosySERBcqiw4h)
- [isKlevuFilterResultOptions](docId\:ztQPUeYzosySERBcqiw4h)
- [isKlevuFilterResultRating](docId\:ztQPUeYzosySERBcqiw4h)
- [isKlevuFilterResultSlider](docId\:ztQPUeYzosySERBcqiw4h)

## Constructors

### constructor

• **new FilterManager**(`initialValues?`)

Manager can be initialized with existing options and sliders

### Parameters

| Name                     | Type                                                     | Description                    |
| ------------------------ | -------------------------------------------------------- | ------------------------------ |
| `initialValues?`         | `Object`                                                 | initialize manager with values |
| `initialValues.filters?` | [`FilterManagerFilters`](docId:7vdpEs-8-0Tv_43dyA7ly)\[] | Given set of filters           |

### Defined in

[store/filterManager.ts:52](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L52)

## Properties

### filters

• **filters**: [`FilterManagerFilters`](docId:7vdpEs-8-0Tv_43dyA7ly)\[] = `[]`

### Defined in

[store/filterManager.ts:25](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L25)

## Accessors

### options

• `get` **options**(): [`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]



use filters instead. This doesn't take into account order of options and sliders

### Returns

[`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[store/filterManager.ts:30](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L30)

***

### sliders

• `get` **sliders**(): [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]



use filters instead. This doesn't take into account order of options and sliders

### Returns

[`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[store/filterManager.ts:40](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L40)

## Methods

### clear

▸ **clear**(): `void`

clear current options and sliders

### Returns

`void`

### Defined in

[store/filterManager.ts:82](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L82)

***

### clearOptionSelections

▸ **clearOptionSelections**(`key?`): `void`

Sets `selected` key of all options to false

### Parameters

| Name   | Type     | Description                                 |
| ------ | -------- | ------------------------------------------- |
| `key?` | `string` | Optional key to lmit clearing to one option |

### Returns

`void`

### Defined in

[store/filterManager.ts:181](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L181)

***

### currentSelection

▸ **currentSelection**(`key`): `undefined` | `string`\[]

Get current selection by key

### Parameters

| Name  | Type     |
| ----- | -------- |
| `key` | `string` |

### Returns

`undefined` | `string`\[]

### Defined in

[store/filterManager.ts:298](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L298)

***

### deselectOption

▸ **deselectOption**(`key`, `value`): `void`

Deselect given option

### Parameters

| Name    | Type     | Description                 |
| ------- | -------- | --------------------------- |
| `key`   | `string` | key of filter to deselect   |
| `value` | `string` | value of option to deselect |

### Returns

`void`

### Defined in

[store/filterManager.ts:158](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L158)

***

### getCurrentState

▸ **getCurrentState**(): `FilterManagerState`

Gets current state of filters

### Returns

`FilterManagerState`

current state

### Defined in

[store/filterManager.ts:91](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L91)

***

### getOptionByKeyCreateIfNotExists

▸ `Private` **getOptionByKeyCreateIfNotExists**(`key`, `value`): `Object`

Get option by key and sub option name. If doesn't exist, create it.

### Parameters

| Name    | Type     |
| ------- | -------- |
| `key`   | `string` |
| `value` | `string` |

### Returns

`Object`

| Name       | Type      | Description                                   |
| ---------- | --------- | --------------------------------------------- |
| `count`    | `number`  |                                               |
| `name`     | `string`  | Name / label of filter                        |
| `selected` | `boolean` | Was this filter selected on the query         |
| `value`    | `string`  | Value of filter. That will be sent to backend |

### Defined in

[store/filterManager.ts:428](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L428)

***

### initFromListFilters

▸ **initFromListFilters**(`filters`): `void`

### Parameters

| Name      | Type                                                                                                                                                                                   |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filters` | ([`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly))\[] |

### Returns

`void`

### Defined in

[store/filterManager.ts:59](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L59)

***

### readFromURLParams

▸ **readFromURLParams**(`params`): `void`

Set current selection of filters from a URL param string

### Parameters

| Name     | Type              | Description                  |
| -------- | ----------------- | ---------------------------- |
| `params` | `URLSearchParams` | URLSearchParams to read from |

### Returns

`void`

### Defined in

[store/filterManager.ts:358](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L358)

***

### selectOption

▸ **selectOption**(`key`, `value`): `void`

Select given option

### Parameters

| Name    | Type     | Description               |
| ------- | -------- | ------------------------- |
| `key`   | `string` | key of filter to select   |
| `value` | `string` | value of option to select |

### Returns

`void`

### Defined in

[store/filterManager.ts:134](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L134)

***

### selectedFilters

▸ **selectedFilters**(): \{ `key`: `string` ; `label`: `string` ; `type`: [`KlevuFilterType`](docId\:WW8-Ksa2-cuoaIcKix5tp) ; `value`: `string`  }\[]

Quickly get all selected options and sliders

### Returns

\{ `key`: `string` ; `label`: `string` ; `type`: [`KlevuFilterType`](docId\:WW8-Ksa2-cuoaIcKix5tp) ; `value`: `string`  }\[]

Array of selected filters, with key, label, type and value

### Defined in

[store/filterManager.ts:380](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L380)

***

### setState

▸ **setState**(`state`): `void`

### Parameters

| Name    | Type                 |
| ------- | -------------------- |
| `state` | `FilterManagerState` |

### Returns

`void`

### Defined in

[store/filterManager.ts:97](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L97)

***

### toApplyFilters

▸ **toApplyFilters**(): [`ApplyFilter`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

Populate filter manager with filters from Klevu API

### Returns

[`ApplyFilter`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[store/filterManager.ts:255](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L255)

***

### toURLParams

▸ **toURLParams**(): `string`

Changes current selection of filters to a URL param string

### Returns

`string`

string of URL params

### Defined in

[store/filterManager.ts:328](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L328)

***

### toggleOption

▸ **toggleOption**(`key`, `value`): `void`

Function to select filters in filter manager

Sends a Dom event on change

### Parameters

| Name    | Type     | Description               |
| ------- | -------- | ------------------------- |
| `key`   | `string` | Key of option             |
| `value` | `string` | value of option to toggle |

### Returns

`void`

### Defined in

[store/filterManager.ts:109](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L109)

***

### updateSlide

▸ **updateSlide**(`key`, `min`, `max`): `void`

Function to update slide in filter manager

Sends a Dom event on change

### Parameters

| Name  | Type     | Description        |
| ----- | -------- | ------------------ |
| `key` | `string` | Key of slide       |
| `min` | `number` | Min value of slide |
| `max` | `number` | Max value of slide |

### Returns

`void`

### Defined in

[store/filterManager.ts:212](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L212)

***

### isKlevuFilterResultOptions

▸ `Static` **isKlevuFilterResultOptions**(`filter`): filter is KlevuFilterResultOptions

Is given variable an option filter

### Parameters

| Name     | Type                                                                                                                                                                              |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filter` | [`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly) |

### Returns

filter is KlevuFilterResultOptions

### Defined in

[store/filterManager.ts:485](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L485)

***

### isKlevuFilterResultRating

▸ `Static` **isKlevuFilterResultRating**(`filter`): filter is KlevuFilterResultRating

Is given variable an rating filter

### Parameters

| Name     | Type                                                                                                                                                                              |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filter` | [`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly) |

### Returns

filter is KlevuFilterResultRating

### Defined in

[store/filterManager.ts:499](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L499)

***

### isKlevuFilterResultSlider

▸ `Static` **isKlevuFilterResultSlider**(`filter`): filter is KlevuFilterResultSlider

Is given variable a slider filter

### Parameters

| Name     | Type                                                                                                                                                                              |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filter` | [`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) \| [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly) |

### Returns

filter is KlevuFilterResultSlider

### Defined in

[store/filterManager.ts:471](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/filterManager.ts#L471)

[title] Interface: KlevuBanner
[path] Interfaces/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuBanner

KMC banner model

## Table of contents

### Properties

- [bannerAltTag](docId\:X1iaoTAGACK9B1KTwA3Io)
- [bannerImg](docId\:X1iaoTAGACK9B1KTwA3Io)
- [bannerName](docId\:X1iaoTAGACK9B1KTwA3Io)
- [bannerRef](docId\:X1iaoTAGACK9B1KTwA3Io)
- [endDate](docId\:X1iaoTAGACK9B1KTwA3Io)
- [position](docId\:X1iaoTAGACK9B1KTwA3Io)
- [redirectUrl](docId\:X1iaoTAGACK9B1KTwA3Io)
- [showForTerms](docId\:X1iaoTAGACK9B1KTwA3Io)
- [showOnCategoryPage](docId\:X1iaoTAGACK9B1KTwA3Io)
- [showOnLandingPage](docId\:X1iaoTAGACK9B1KTwA3Io)
- [showOnQuickSearch](docId\:X1iaoTAGACK9B1KTwA3Io)
- [startDate](docId\:X1iaoTAGACK9B1KTwA3Io)

## Properties

### bannerAltTag

• **bannerAltTag**: `string`

### Defined in

[models/KMCBanner.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L8)

***

### bannerImg

• **bannerImg**: `string`

### Defined in

[models/KMCBanner.ts:14](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L14)

***

### bannerName

• **bannerName**: `string`

### Defined in

[models/KMCBanner.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L12)

***

### bannerRef

• **bannerRef**: `number`

### Defined in

[models/KMCBanner.ts:15](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L15)

***

### endDate

• **endDate**: `string`

### Defined in

[models/KMCBanner.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L11)

***

### position

• **position**: `string`

### Defined in

[models/KMCBanner.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L13)

***

### redirectUrl

• **redirectUrl**: `string`

### Defined in

[models/KMCBanner.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L9)

***

### showForTerms

• **showForTerms**: `string`\[]

### Defined in

[models/KMCBanner.ts:6](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L6)

***

### showOnCategoryPage

• **showOnCategoryPage**: `boolean`

### Defined in

[models/KMCBanner.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L16)

***

### showOnLandingPage

• **showOnLandingPage**: `boolean`

### Defined in

[models/KMCBanner.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L7)

***

### showOnQuickSearch

• **showOnQuickSearch**: `boolean`

### Defined in

[models/KMCBanner.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L10)

***

### startDate

• **startDate**: `string`

### Defined in

[models/KMCBanner.ts:17](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L17)

[title] Enumeration: KlevuDomEvents
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuDomEvents

## Table of contents

### Enumeration Members

- [ClickEventSent](docId\:NobpYQt4aZ1JcaHPTNcMB)
- [FilterSelectionUpdate](docId\:NobpYQt4aZ1JcaHPTNcMB)
- [FiltersApplied](docId\:NobpYQt4aZ1JcaHPTNcMB)
- [LastSearchUpdate](docId\:NobpYQt4aZ1JcaHPTNcMB)

## Enumeration Members

### ClickEventSent

• **ClickEventSent** = `"klevu-click-event-sent"`

When any click event has been fired on the page

### Defined in

[events/KlevuDomEvents.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuDomEvents.ts#L24)

***

### FilterSelectionUpdate

• **FilterSelectionUpdate** = `"klevu-filter-selection-updates"`

When filter manager selection has changed

### Defined in

[events/KlevuDomEvents.ts:14](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuDomEvents.ts#L14)

***

### FiltersApplied

• **FiltersApplied** = `"klevu-filters-applied"`

When filters have been applied from results

### Defined in

[events/KlevuDomEvents.ts:19](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuDomEvents.ts#L19)

***

### LastSearchUpdate

• **LastSearchUpdate** = `"klevu-last-search-update"`

When list of last searched terms update

### Defined in

[events/KlevuDomEvents.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuDomEvents.ts#L9)

[title] Class: KlevuResponseObject
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuResponseObject

This class is used to access the response data from Klevu API
It builds up the state of the result and it can be used to do various things with the data

## Table of contents

### Constructors

- [constructor](docId:_OzqIexf73M6LaMIC6_Oo)

### Properties

- [#functions](docId:_OzqIexf73M6LaMIC6_Oo)
- [#queryObjects](docId:_OzqIexf73M6LaMIC6_Oo)
- [apiResponse](docId:_OzqIexf73M6LaMIC6_Oo)

### Methods

- [#buildQueryObjects](docId:_OzqIexf73M6LaMIC6_Oo)
- [queriesById](docId:_OzqIexf73M6LaMIC6_Oo)
- [queryExists](docId:_OzqIexf73M6LaMIC6_Oo)
- [suggestionsById](docId:_OzqIexf73M6LaMIC6_Oo)

## Constructors

### constructor

• **new KlevuResponseObject**(`response`, `functions`)

### Parameters

| Name        | Type                                                              |
| ----------- | ----------------------------------------------------------------- |
| `response`  | [`KlevuApiRawResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)              |
| `functions` | [`KlevuFetchFunctionReturnValue`](docId:7vdpEs-8-0Tv_43dyA7ly)\[] |

### Defined in

[connection/responseObject.ts:14](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L14)

## Properties

### #functions

• `Private` **#functions**: [`KlevuFetchFunctionReturnValue`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[connection/responseObject.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L11)

***

### #queryObjects

• `Private` **#queryObjects**: `Object` = `{}`

### Index signature

▪ \[id: `string`]: [`KlevuResponseQueryObject`](docId\:PhrCdX6tN6MMUtKZfUWjb)

### Defined in

[connection/responseObject.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L12)

***

### apiResponse

• **apiResponse**: [`KlevuApiRawResponse`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/responseObject.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L10)

## Methods

### #buildQueryObjects

▸ `Private` **#buildQueryObjects**(): `void`

### Returns

`void`

### Defined in

[connection/responseObject.ts:42](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L42)

***

### queriesById

▸ **queriesById**(`id`): [`KlevuResponseQueryObject`](docId\:PhrCdX6tN6MMUtKZfUWjb)

Get query results by id

### Parameters

| Name | Type     | Description   |
| ---- | -------- | ------------- |
| `id` | `string` | query id used |

### Returns

[`KlevuResponseQueryObject`](docId\:PhrCdX6tN6MMUtKZfUWjb)

### Defined in

[connection/responseObject.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L58)

***

### queryExists

▸ **queryExists**(`id`): `boolean`

Check if query exists. This should be used as queriesById can throw an error

### Parameters

| Name | Type     | Description   |
| ---- | -------- | ------------- |
| `id` | `string` | query id used |

### Returns

`boolean`

### Defined in

[connection/responseObject.ts:71](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L71)

***

### suggestionsById

▸ **suggestionsById**(`id`): `undefined` | [`KlevuSuggestionResult`](docId:7vdpEs-8-0Tv_43dyA7ly)

Get suggestions by id

### Parameters

| Name | Type     |
| ---- | -------- |
| `id` | `string` |

### Returns

`undefined` | [`KlevuSuggestionResult`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/responseObject.ts:38](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseObject.ts#L38)

[title] klevufetchfunctionreturnvalue
[path] Modules/

Ƭ **KlevuFetchFunctionReturnValue**: `Object`

What functions passed to KlevuFetch should implement

### Type declaration

| Name                     | Type                                                       | Description                                                                                   |
| ------------------------ | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `configOverride?`        | [`KlevuConfig`](classes/KlevuConfig.md)                    | Pass down the if config has been overridden.                                                  |
| `klevuFunctionId`        | `KlevuFetchTypeId`                                         | Id of function. Used only internally                                                          |
| `modifiers?`             | `KlevuFetchModifer`\[]                                     | List of modifiers set for this function                                                       |
| `params?`                | [`KlevuFetchFunctionParams`](docId\:SykuVchrFw4dLCH2nmQ8k) | Some of the functions pass metadata that can be used in other places                          |
| `previousResultRecords?` | [`KlevuRecord`](docId\:vA8Kz9WZX3r_nThlqQ1i4)\[]           | Local memory cache products from previous results. Used by analytics when making page changes |
| `queries?`               | [`KlevuAllRecordQueries`](docId\:aemJGcPHnPvj5gp7OE6gs)\[] | What queries should KlevuFetch do to backend                                                  |
| `suggestions?`           | [`KlevuSuggestionQuery`](docId:1_-FvnZldotd6ffHFIrs5)\[]   | What suggestions queries should do to backend                                                 |

### Defined in

[queries/index.ts:56](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/index.ts#L56)

[title] klevulastsearches
[path] Modules/

• `Const` **KlevuLastSearches**: `Object`

### Type declaration

| Name   | Type                                                       |
| ------ | ---------------------------------------------------------- |
| `get`  | () => [`KlevuLastSearch`](docId\:Wh31YKMY8igOGvQBPC7Hh)\[] |
| `save` | (`term`: `string`) => `void`                               |

### Defined in

[store/lastSearches.ts:19](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/lastSearches.ts#L19)

[title] klevusuggestionresult
[path] Modules/

Ƭ **KlevuSuggestionResult**: `Object`

### Type declaration

| Name          | Type                         |
| ------------- | ---------------------------- |
| `id`          | `string`                     |
| `suggestions` | \{ `suggest`: `string`  }\[] |

### Defined in

[models/KlevuSuggestionResult.ts:1](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSuggestionResult.ts#L1)

[title] klevufilterresultoptions
[path] Modules/

Ƭ **KlevuFilterResultOptions**: `KlevuFilterResult` & \{ `options`: \{ `count`: `number` ; `name`: `string` ; `selected`: `boolean` ; `value`: `string`  }\[] ; `type`: [`Options`](enums/KlevuFilterType.md#options) | [`Rating`](enums/KlevuFilterType.md#rating)  }

### Defined in

[models/KlevuApiRawResponse.ts:31](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L31)

[title] klevusuggestionquery
[path] Modules/

Ƭ **KlevuSuggestionQuery**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) & \{ `hlEndElem?`: `string` ; `hlStartElem?`: `string` ; `limit?`: `number` ; `query`: `string` ; `typeOfRequest`: [`Suggestion`](enums/KlevuTypeOfRequest.md#suggestion)  }

### Defined in

[models/KlevuSuggestionQuery.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSuggestionQuery.ts#L4)

[title] Modules
[path] /

File not found!

[title] klevukmcrecommendations
[path] Modules/

Ƭ **KlevuKMCRecommendations**: `Object`

### Type declaration

| Name                        | Type                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metadata`                  | \{ `action?`: `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` \| `null` ; `enabled`: `boolean` ; `logic`: [`KMCRecommendationLogic`](enums/KMCRecommendationLogic.md) ; `maxProducts`: `number` ; `pageType`: `KMCRecommendationPagetype` ; `productThreshold`: `number` ; `recsKey`: `string` ; `segmentKey`: `string` \| `null` ; `segmentName`: `string` \| `null` ; `spotKey`: `string` ; `spotName`: `string` ; `title`: `string`  } |
| `metadata.action?`          | `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` \| `null`                                                                                                                                                                                                                                                                                                                                                                                 |
| `metadata.enabled`          | `boolean`                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `metadata.logic`            | [`KMCRecommendationLogic`](enums/KMCRecommendationLogic.md)                                                                                                                                                                                                                                                                                                                                                                                           |
| `metadata.maxProducts`      | `number`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata.pageType`         | `KMCRecommendationPagetype`                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `metadata.productThreshold` | `number`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata.recsKey`          | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata.segmentKey`       | `string` \| `null`                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `metadata.segmentName`      | `string` \| `null`                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `metadata.spotKey`          | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata.spotName`         | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata.title`            | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `scripts`                   | \{ `recsObject?`: `unknown`  }                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `scripts.recsObject?`       | `unknown`                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `search`                    | \{ `basePath`: `string` ; `payload`: `string` ; `recsAction?`: `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"`  }                                                                                                                                                                                                                                                                                                                         |
| `search.basePath`           | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `search.payload`            | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `search.recsAction?`        | `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"`                                                                                                                                                                                                                                                                                                                                                                                           |
| `staticContent?`            | \{ `contentType`: `"image"` ; `image`: \{ `altTag`: `string` ; `maxWidth`: `number` ; `resolution`: `string` ; `url`: `string`  }\[] ; `targetUrl`: `string`  }\[]                                                                                                                                                                                                                                                                                    |
| `styles`                    | \{ `base`: `string`  }                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `styles.base`               | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `templates`                 | \{ `base`: `string`  }                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `templates.base`            | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                              |

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:61](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L61)

[title] klevuuploadimageforsearch
[path] Modules/

▸ **KlevuUploadImageForSearch**(`image`): `Promise`\<`any`>

This function is to be called to get the url to be used
in search for image search or to be passed to the imageSearch
query function

### Parameters

| Name    | Type   | Description                |
| ------- | ------ | -------------------------- |
| `image` | `Blob` | The image object to upload |

### Returns

`Promise`\<`any`>

image url to be passed to search

### Defined in

[utils/uploadImageForSearch.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/utils/uploadImageForSearch.ts#L9)

[title] klevualsoviewedquery
[path] Modules/

Ƭ **KlevuAlsoViewedQuery**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) & \{ `settings?`: \{ `context?`: \{ `recentObjects`: \{ `records`: \{ `id`: `string`  }\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[]  }  } ; `typeOfRequest`: [`AlsoViewed`](enums/KlevuTypeOfRequest.md#alsoviewed)  }

Klevu API query specific for Also Viewed recommendation

### Defined in

[models/KlevuAlsoViewedQuery.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuAlsoViewedQuery.ts#L7)

[title] listfilters
[path] Modules/

▸ **listFilters**(`options?`): `KlevuFetchModifer`

List filters that can affect given query

### Parameters

| Name       | Type                  |
| ---------- | --------------------- |
| `options?` | `Partial`\<`Options`> |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/listFilters/listFilters.ts:33](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/listFilters/listFilters.ts#L33)

[title] applyfilterwithmanager
[path] Modules/

▸ **applyFilterWithManager**(`manager`): `KlevuFetchModifer`

Apply filters to query based on Filter Manager

### Parameters

| Name      | Type                                        |
| --------- | ------------------------------------------- |
| `manager` | [`FilterManager`](classes/FilterManager.md) |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/applyFilterWithManager/applyFilterWithManager.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/applyFilterWithManager/applyFilterWithManager.ts#L12)

[title] Interface: KMCMapsRootObject
[path] Interfaces/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KMCMapsRootObject

## Table of contents

### Properties

- [klevu\_keywordUrlMap](docId\:wbf7MpBATi9iiAy9R5uP3)

## Properties

### klevu\_keywordUrlMap

• **klevu\_keywordUrlMap**: [`KlevuKeywordUrlMap`](docId\:LDP3zBw_oYVJHpfR0D2hy)\[]

### Defined in

[models/KMCMaps.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCMaps.ts#L7)

[title] klevukmcrecommendationoptions
[path] Modules/

Ƭ **KlevuKMCRecommendationOptions**: `Object`

### Type declaration

| Name                | Type        | Description                                                                                                                                          |
| ------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cartProductIds?`   | `string`\[] | If KMC recommendation is Checkout page based then its required to provide productIds that are currently in the cart                                  |
| `categoryPath?`     | `string`    | If KMC recommendation is category based then category path is required. Requires categories to be separated with semicolon. For example "Mens;Shoes" |
| `currentProductId?` | `string`    | If KMC recommendation is Product based then it is required to pass current pages product id                                                          |
| `id`                | `string`    | -                                                                                                                                                    |
| `itemGroupId?`      | `string`    | If KMC recommendation is Product based then Item group id (the parent id) is required information.                                                   |

### Defined in

[queries/kmcRecommendation/kmcRecommendation.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/kmcRecommendation/kmcRecommendation.ts#L12)

[title] injectfilterresult
[path] Modules/

▸ **injectFilterResult**(`prevQuery`): `KlevuFetchModifer`

Internal function to inject listFilter results back to result object when they are removed in next() function
Should not be used outside of library itself

### Parameters

| Name        | Type                                               |
| ----------- | -------------------------------------------------- |
| `prevQuery` | [`KlevuQueryResult`](docId\:CGLzKe0jhD8maf-Iy_RLX) |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/injectFilterResult/injectFilterResult.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/injectFilterResult/injectFilterResult.ts#L12)

[title] boostwithfilters
[path] Modules/

▸ **boostWithFilters**(`boosts`): `KlevuFetchModifer`

Boost products based on a filters

### Parameters

| Name     | Type                                                                  |
| -------- | --------------------------------------------------------------------- |
| `boosts` | \{ `key`: `string` ; `values`: `string`\[] ; `weight`: `number`  }\[] |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/boostWithFilters/boostWithFilters.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/boostWithFilters/boostWithFilters.ts#L10)

[title] moiactionsmessage
[path] Modules/

Ƭ **MoiActionsMessage**: `Object`

### Type declaration

| Name              | Type                                                                                                                                                                                |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `actions`         | \{ `actions`: \{ `context`: \{ `link?`: `string` ; `messageId?`: `string` ; `value?`: `string`  } ; `type`: `"purgeHistory"` \| `"redirectToUrl"` \| `"askFeedbackReason"`  }\[]  } |
| `actions.actions` | \{ `context`: \{ `link?`: `string` ; `messageId?`: `string` ; `value?`: `string`  } ; `type`: `"purgeHistory"` \| `"redirectToUrl"` \| `"askFeedbackReason"`  }\[]                  |

### Defined in

[connection/moi/moi.ts:129](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L129)

[title] klevulastsearch
[path] Modules/

Ƭ **KlevuLastSearch**: `Object`

### Type declaration

| Name        | Type     |
| ----------- | -------- |
| `term`      | `string` |
| `timestamp` | `number` |

### Defined in

[store/lastSearches.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/lastSearches.ts#L4)

[title] klevufetchfunctionparams
[path] Modules/

Ƭ **KlevuFetchFunctionParams**: `Object`

### Type declaration

| Name                     | Type                                                      | Description                                      |
| ------------------------ | --------------------------------------------------------- | ------------------------------------------------ |
| `abtest?`                | \{ `abTestId`: `string` ; `abTestVariantId`: `string`  }  | A/B test information of request                  |
| `abtest.abTestId`        | `string`                                                  | -                                                |
| `abtest.abTestVariantId` | `string`                                                  | -                                                |
| `category?`              | `string`                                                  | Which category merchandising was called          |
| `id?`                    | `string`                                                  | Current id of function                           |
| `kmcConfig?`             | [`KlevuKMCRecommendations`](docId\:Vo7OtiF0AXpgHUYvWUVrl) | KMC recommendation information                   |
| `searchSendEventSent?`   | `boolean`                                                 | If true modifier has sent a search event already |
| `term?`                  | `string`                                                  | term used in the search                          |

### Defined in

[queries/index.ts:18](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/index.ts#L18)

[title] klevuresultevent
[path] Modules/

Ƭ **KlevuResultEvent**: `Object`

### Type declaration

| Name                               | Type                                                                                                                                                            |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `categoryMerchandisingClickEvent?` | (`params`: \{ `categoryTitle`: `string` ; `override?`: `Partial`\<`KlevuV1CategoryProductsView`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void` |
| `hooks`                            | [`KlevuResultEventOnResult`](docId\:ymHUuQ_gTYkxpo0aUpjSG)\[]                                                                                                   |
| `recommendationBannerClickEvent?`  | (`params`: \{ `resolution`: `"desktop"` \| `"mobile"`  }) => `void`                                                                                             |
| `recommendationClickEvent?`        | (`params`: \{ `override?`: `Partial`\<`KlevuRecommendationsEventV2Data`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void`                         |
| `searchClickEvent?`                | (`params`: \{ `autoSendViewEvent?`: `boolean` ; `override?`: `Partial`\<`V1SearchEvent`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void`         |

### Defined in

[models/KlevuResultEvent.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuResultEvent.ts#L7)

[title] alsoviewed
[path] Modules/

▸ **alsoViewed**(`options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Shows products that visitor should also see. Automatically applies products that user has already clicked.

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `options?`     | `Partial`\<`Options`>  |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/alsoViewed/alsoViewed.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/alsoViewed/alsoViewed.ts#L24)

[title] klevufetch
[path] Modules/

▸ **KlevuFetch**(`...functionPromises`): `Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

Function that makes query to KlevuBackend. It can take amount of queries.

### Parameters

| Name                  | Type                                                |
| --------------------- | --------------------------------------------------- |
| `...functionPromises` | [`KlevuFetchQueries`](docId\:q5OZXYWoRdA58lqyW-VbL) |

### Returns

`Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

Tools to operate results and get next results [KlevuFetchResponse](docId\:VI5JRTKTZCm6Sdx7F7IGq)

### Defined in

[connection/klevuFetch.ts:28](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/klevuFetch.ts#L28)

[title] klevufetchresponse
[path] Modules/

Ƭ **KlevuFetchResponse**: `Object`

Tools for operating results in easier way.

### Type declaration

| Name              | Type                                                                                       | Description                 |
| ----------------- | ------------------------------------------------------------------------------------------ | --------------------------- |
| `apiResponse`     | `null` \| [`KlevuApiRawResponse`](docId\:OuLSbkYPK2-rGgqH6qeog)                            | Raw response from Klevu API |
| `queriesById`     | (`id`: `string`) => [`KlevuFetchQueryResult`](docId\:GqGhGYiSs2VhANdvEPM_9) \| `undefined` | Get query result by id      |
| `suggestionsById` | (`id`: `string`) => [`KlevuSuggestionResult`](docId\:yQSz4WXRMGv61HqrbSwwi) \| `undefined` | Get suggestion by Id        |

### Defined in

[models/KlevuFetchResponse.ts:81](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFetchResponse.ts#L81)

[title] klevukmcsettings
[path] Modules/

▸ **KlevuKMCSettings**(`ignoreCache?`, `cacheLength?`): `Promise`\<\{ `banner?`: [`KMCBannerRootObject`](interfaces/KMCBannerRootObject.md) ; `maps?`: [`KMCMapsRootObject`](interfaces/KMCMapsRootObject.md) ; `root?`: [`KMCRootObject`](interfaces/KMCRootObject.md)  }>

Fetches KMC settings from server. Caches data for a day.

### Parameters

| Name           | Type      | Default value | Description                                           |
| -------------- | --------- | ------------- | ----------------------------------------------------- |
| `ignoreCache?` | `boolean` | `undefined`   | If true, will ignore cache and fetch data from server |
| `cacheLength`  | `number`  | `ONE_DAY`     | How long to cache data in milliseconds                |

### Returns

`Promise`\<\{ `banner?`: [`KMCBannerRootObject`](interfaces/KMCBannerRootObject.md) ; `maps?`: [`KMCMapsRootObject`](interfaces/KMCMapsRootObject.md) ; `root?`: [`KMCRootObject`](interfaces/KMCRootObject.md)  }>

### Defined in

[connection/kmc.ts:21](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/kmc.ts#L21)

[title] klevuallrecordqueries
[path] Modules/

Ƭ **KlevuAllRecordQueries**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) | [`KlevuSimilarProductsQuery`](docId:9TNwVNTU8sbBzqKIG2fKk) | [`KlevuTrendingProductsQuery`](docId\:Z-ji4NGdhse100C2uEAIw) | [`KlevuAlsoViewedQuery`](docId\:ITcsCHsRNvvCZ6MaPonoG)

All possible record queries that can be used with [KlevuFetch](docId\:qj7FySybJVkFVrUSc3-Ku) function

### Defined in

[models/KlevuAllRecordQueries.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuAllRecordQueries.ts#L9)

[title] boostwithrecords
[path] Modules/

▸ **boostWithRecords**(`records`): `KlevuFetchModifer`

Boost or deboost query based on a record ids.

### Parameters

| Name      | Type                                         | Description                   |
| --------- | -------------------------------------------- | ----------------------------- |
| `records` | \{ `id`: `string` ; `weight`: `number`  }\[] | Keywords to boost and deboost |

### Returns

`KlevuFetchModifer`

KlevuModifier that be used to modify query

### Defined in

[modifiers/boostWithRecords/boostWithRecords.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/boostWithRecords/boostWithRecords.ts#L10)

[title] klevusearchoptions
[path] Modules/

Ƭ **KlevuSearchOptions**: \{ `id`: `string` ; `typeOfRecords`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)\[]  } & `Omit`\<[`KlevuBaseQuerySettings`](docId\:DyD-sdD9prRQ0gcOerUbZ), `"query"`>

Search options to modify the search query.

### Defined in

[queries/search/search.ts:15](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/search/search.ts#L15)

[title] exclude
[path] Modules/

▸ **exclude**(`itemGroupIds`): `KlevuFetchModifer`

Force exclude product ids on result

### Parameters

| Name           | Type        |
| -------------- | ----------- |
| `itemGroupIds` | `string`\[] |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/exclude/exclude.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/exclude/exclude.ts#L10)

[title] Enumeration: KlevuTypeOfRecord
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuTypeOfRecord

## Table of contents

### Enumeration Members

- [Category](docId\:vONWNcusXpLJmZ_Ae8_9Y)
- [Cms](docId\:vONWNcusXpLJmZ_Ae8_9Y)
- [Image](docId\:vONWNcusXpLJmZ_Ae8_9Y)
- [Product](docId\:vONWNcusXpLJmZ_Ae8_9Y)

## Enumeration Members

### Category

• **Category** = `"KLEVU_CATEGORY"`

### Defined in

[models/KlevuTypeOfRecord.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRecord.ts#L7)

***

### Cms

• **Cms** = `"KLEVU_CMS"`

### Defined in

[models/KlevuTypeOfRecord.ts:6](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRecord.ts#L6)

***

### Image

• **Image** = `"KLEVU_IMAGE"`

### Defined in

[models/KlevuTypeOfRecord.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRecord.ts#L8)

***

### Product

• **Product** = `"KLEVU_PRODUCT"`

### Defined in

[models/KlevuTypeOfRecord.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRecord.ts#L5)

[title] klevutrendingproductsquery
[path] Modules/

Ƭ **KlevuTrendingProductsQuery**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) & \{ `settings?`: \{ `query?`: \{ `categoryPath?`: `string` ; `term`: `"*"`  }  } ; `typeOfRequest`: [`Trending`](enums/KlevuTypeOfRequest.md#trending)  }

### Defined in

[models/KlevuTrendingProductsQuery.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTrendingProductsQuery.ts#L4)

[title] klevufetchqueryresult
[path] Modules/

Ƭ **KlevuFetchQueryResult**: [`KlevuQueryResult`](docId\:CGLzKe0jhD8maf-Iy_RLX) & [`KlevuResultEvent`](docId\:tmZpXTl378r572rBXU5i5) & \{ `annotationsById?`: (`productId`: `string`, `languageCode`: `string`) => `Promise`\<`undefined` | [`KlevuAnnotations`](docId\:ZM_n2M_w_iJJQ8wX2wffJ)> ; `functionParams?`: [`KlevuFetchFunctionParams`](docId\:SykuVchrFw4dLCH2nmQ8k) ; `getPage?`: [`KlevuNextFunc`](docId\:uZrBd4V05dAaoVLNKRUmT) ; `next?`: [`KlevuNextFunc`](docId\:uZrBd4V05dAaoVLNKRUmT)  }

Fetch query results

### Defined in

[models/KlevuFetchResponse.ts:35](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFetchResponse.ts#L35)

[title] klevurecordfields
[path] Modules/

Ƭ **KlevuRecordFields**: `LiteralUnion`\<keyof [`KlevuRecord`](docId\:vA8Kz9WZX3r_nThlqQ1i4), `string`>

### Defined in

[models/KlevuRecordFields.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuRecordFields.ts#L4)

[title] klevufilterresultrating
[path] Modules/

Ƭ **KlevuFilterResultRating**: `KlevuFilterResult` & \{ `options`: \{ `count`: `number` ; `name`: `string` ; `selected`: `boolean` ; `value`: `string`  }\[] ; `type`: [`Rating`](enums/KlevuFilterType.md#rating)  }

Klevu rating filters option

### Defined in

[models/KlevuApiRawResponse.ts:82](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L82)

[title] Enumeration: KlevuSearchPreference
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuSearchPreference

## Table of contents

### Enumeration Members

- [debugQuery](docId:4CSizq9eos8dHPK21r01b)
- [disableFuzzyMatch](docId:4CSizq9eos8dHPK21r01b)
- [disableORSearch](docId:4CSizq9eos8dHPK21r01b)
- [disableStockSorting](docId:4CSizq9eos8dHPK21r01b)
- [disableWildcard](docId:4CSizq9eos8dHPK21r01b)
- [disableWordShingles](docId:4CSizq9eos8dHPK21r01b)
- [enableBoostingOriginalTermsInSynonyms](docId:4CSizq9eos8dHPK21r01b)
- [enableScores](docId:4CSizq9eos8dHPK21r01b)
- [excludeIds](docId:4CSizq9eos8dHPK21r01b)
- [hideOutOfStockProducts](docId:4CSizq9eos8dHPK21r01b)
- [ignoreManualBoosting](docId:4CSizq9eos8dHPK21r01b)
- [includeCategoryFilterInCatNav](docId:4CSizq9eos8dHPK21r01b)
- [includeDescription](docId:4CSizq9eos8dHPK21r01b)
- [includeStopwords](docId:4CSizq9eos8dHPK21r01b)
- [partialMatch](docId:4CSizq9eos8dHPK21r01b)
- [partialMatchForAllWords](docId:4CSizq9eos8dHPK21r01b)
- [searchCompoundsAsAndQuery](docId:4CSizq9eos8dHPK21r01b)
- [showDisabledFacets](docId:4CSizq9eos8dHPK21r01b)
- [showFiltersWithSmallCount](docId:4CSizq9eos8dHPK21r01b)
- [showOutOfStockProducts](docId:4CSizq9eos8dHPK21r01b)

## Enumeration Members

### debugQuery

• **debugQuery** = `"debugQuery"`

Use this flag to include additional information about the query execution.
This information is populated in the meta object of the response.

Please note that it is not recommended to enable this flag in your
Production environment, as performance will be impacted.

### Defined in

[models/KlevuSearchPreference.ts:133](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L133)

***

### disableFuzzyMatch

• **disableFuzzyMatch** = `"disableFuzzyMatch"`

This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to
disable the FUZZY\_AND and FUZZY\_OR search types from being attempted.

### Defined in

[models/KlevuSearchPreference.ts:39](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L39)

***

### disableORSearch

• **disableORSearch** = `"disableORSearch"`

This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to
disable the WILDCARD\_OR and FUZZY\_OR search types from being attempted.

### Defined in

[models/KlevuSearchPreference.ts:50](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L50)

***

### disableStockSorting

• **disableStockSorting** = `"disableStockSorting"`

This can be used in conjunction with showOutOfStockProducts. If your store
is configured to display out of stock products, they will be displayed at
the very end of the search results after all in stock products have been
displayed. By using this flag you can disable this logic, and cause all
products to be ranked in an order that disregards their stock status.

### Defined in

[models/KlevuSearchPreference.ts:17](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L17)

***

### disableWildcard

• **disableWildcard** = `"disableWildcard"`

This flag can be used in conjunction with the typeOfSearch 'DEFAULT' to
disable the WILDCARD\_AND and WILDCARD\_OR search types from being
attempted.

### Defined in

[models/KlevuSearchPreference.ts:45](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L45)

***

### disableWordShingles

• **disableWordShingles** = `"disableWordShingles"`

For a query longer than one word, all the possible bigrams and trigrams
(i.e. formed out of query terms) are looked up in records and the ones
having one or more of them are boosted higher up in the search results.
You can use this flag to disable such boosting.

### Defined in

[models/KlevuSearchPreference.ts:78](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L78)

***

### enableBoostingOriginalTermsInSynonyms

• **enableBoostingOriginalTermsInSynonyms** = `"enableBoostingOriginalTermsInSynonyms"`

By default, synonyms are treated equally to their query term. Should you
wish to give higher priority to the actual terms your customer entered in
the query over their synonyms, please include this flag in your search
preferences.

### Defined in

[models/KlevuSearchPreference.ts:100](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L100)

***

### enableScores

• **enableScores** = `"enableScores"`

Include the score information with the response fields: score,
klevu\_manual\_boosting, klevu\_bulk\_boosting and klevu\_selflearning\_boosting.

### Defined in

[models/KlevuSearchPreference.ts:125](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L125)

***

### excludeIds

• **excludeIds** = `"excludeIds"`

Use this flag to disable the searching of record IDs.

### Defined in

[models/KlevuSearchPreference.ts:27](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L27)

***

### hideOutOfStockProducts

• **hideOutOfStockProducts** = `"hideOutOfStockProducts"`

Whether or not your store should include 'Out of Stock' products in search
results by default can be configured within the Klevu Merchant Centre.
However, if you would like to override this for a particular query, please
include one of these flags.

### Defined in

[models/KlevuSearchPreference.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L9)

***

### ignoreManualBoosting

• **ignoreManualBoosting** = `"ignoreManualBoosting"`

@TODO: Most probably ignores manual boostin. Needs proper documentation

### Defined in

[models/KlevuSearchPreference.ts:138](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L138)

***

### includeCategoryFilterInCatNav

• **includeCategoryFilterInCatNav** = `"includeCategoryFilterInCatNav"`

When the typeOfRequest is 'CATNAV', the filter for 'Category' is
automatically excluded since you are already within the context of a
category. Use this flag to override this logic and return the category
filters even for CatNav requests.

### Defined in

[models/KlevuSearchPreference.ts:120](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L120)

***

### includeDescription

• **includeDescription** = `"includeDescription"`

, excludeDescription Whether or not a record's 'description' is considered
for search results can be configured by Klevu Support on a store by store
basis, however if you would like to override this for a particular query,
please include one of these flags.

### Defined in

[models/KlevuSearchPreference.ts:34](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L34)

***

### includeStopwords

• **includeStopwords** = `"includeStopwords"`

By default, functional words such as prepositions, pronouns, articles,
etc. are excluded from searches. Add this flag to include these stopwords
in your search.

### Defined in

[models/KlevuSearchPreference.ts:23](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L23)

***

### partialMatch

• **partialMatch** = `"partialMatch"`

Enable partial match for the last word of a query, where the last word
searched can be a substring of any other word found in a record. This can
be useful for non-English languages.

For example let's say a product has the name "rödvinsglas" (red wine
glass). If searching for "högt glas" (tall glass) it may not match since
the record has no words starting with 'glas'. By providing this flag, the
search would become "högt *glas*" meaning it would match the record since
it contains a word which ends with 'glas'.

### Defined in

[models/KlevuSearchPreference.ts:63](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L63)

***

### partialMatchForAllWords

• **partialMatchForAllWords** = `"partialMatchForAllWords"`

Similar to partialMatch, but for all words rather than just the last. In
the same "rödvinsglas" example, a search for "högt glas" would become
"*högt* *glas*", so any records containing words containing 'högt' or
'glas' would result in a match.

### Defined in

[models/KlevuSearchPreference.ts:71](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L71)

***

### searchCompoundsAsAndQuery

• **searchCompoundsAsAndQuery** = `"searchCompoundsAsAndQuery"`

When a compound word is searched for, i.e. two or more individual words
joined together as one word, Klevu automatically disjoints them if the
de-compounding feature is enabled for your store.

For example, a search for "fairylights" would be treated as "fairy lights",
but with the added condition that those words must appear within 5 words of
each other in a matching record.

If you would prefer that the words "fairy" and "light" could be found
anywhere within the record, not necessarily near one another, then please
include this flag.

### Defined in

[models/KlevuSearchPreference.ts:92](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L92)

***

### showDisabledFacets

• **showDisabledFacets** = `"showDisabledFacets"`

It is possible to configure which facets or filters should be enabled or
disabled within the Klevu Merchant Centre. By including this flag, all
facets will be returned regardless of whether they have been disabled in
the KMC.

### Defined in

[models/KlevuSearchPreference.ts:107](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L107)

***

### showFiltersWithSmallCount

• **showFiltersWithSmallCount** = `"showFiltersWithSmallCount"`

By default some filters are excluded from the results if they only have a
small number of results. Please use this flag to override this logic and
include all filters in the response.

### Defined in

[models/KlevuSearchPreference.ts:113](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L113)

***

### showOutOfStockProducts

• **showOutOfStockProducts** = `"showOutOfStockProducts"`

### Defined in

[models/KlevuSearchPreference.ts:2](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSearchPreference.ts#L2)

[title] moicontext
[path] Modules/

Ƭ **MoiContext**: `Object`

### Type declaration

| Name           | Type                                           |
| -------------- | ---------------------------------------------- |
| `klevuApiKey`  | `string`                                       |
| `mode?`        | [`MoiChatModes`](docId\:emBLFzL6rES1tkprIbcb6) |
| `pqaWidgetId?` | `string`                                       |
| `productId?`   | `string`                                       |
| `sessionId?`   | `string`                                       |
| `url?`         | `string`                                       |

### Defined in

[connection/moi/moi.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L10)

[title] Class: KlevuEvents
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuEvents

## Table of contents

### Constructors

- [constructor](docId\:v4S0tEBONPr8hwup9X7dW)

### Methods

- [buy](docId\:v4S0tEBONPr8hwup9X7dW)
- [categoryMerchandisingProductClick](docId\:v4S0tEBONPr8hwup9X7dW)
- [categoryMerchandisingView](docId\:v4S0tEBONPr8hwup9X7dW)
- [imageBannerClick](docId\:v4S0tEBONPr8hwup9X7dW)
- [recommendationClick](docId\:v4S0tEBONPr8hwup9X7dW)
- [recommendationView](docId\:v4S0tEBONPr8hwup9X7dW)
- [search](docId\:v4S0tEBONPr8hwup9X7dW)
- [searchProductClick](docId\:v4S0tEBONPr8hwup9X7dW)

## Constructors

### constructor

• **new KlevuEvents**()

## Methods

### buy

▸ `Static` **buy**(`items`): `void`

Tell Klevu what products where bought by the user

### Parameters

| Name                     | Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Description       |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------- |
| `items`                  | `Object`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Items user bought |
| `items.items`            | \{ `amount`: `number` ; `orderId?`: `string` ; `orderLineId?`: `string` ; `override?`: `Partial`\<\{ `currency`: `string` ; `item_group_id`: `string` ; `item_id`: `string` ; `item_name`: `string` ; `item_variant_id`: `string` ; `order_id?`: `string` ; `order_line_id?`: `string` ; `unit_price`: `number` ; `units?`: `number`  }> ; `product`: `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`> & `Partial`\<`Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"name"` \| `"currency"` \| `"itemGroupId"` \| `"salePrice"`>> ; `variantId?`: `string`  }\[] | -                 |
| `items.user?`            | `Object`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | -                 |
| `items.user.email?`      | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | -                 |
| `items.user.ip_address?` | `string`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | -                 |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:44](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L44)

***

### categoryMerchandisingProductClick

▸ `Static` **categoryMerchandisingProductClick**(`«destructured»`): `void`

### Parameters

| Name                 | Type                                                                                                                                                                                                  |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `«destructured»`     | `Object`                                                                                                                                                                                              |
| › `abTestId?`        | `string`                                                                                                                                                                                              |
| › `abTestVariantId?` | `string`                                                                                                                                                                                              |
| › `activeFilters?`   | `string`                                                                                                                                                                                              |
| › `categoryTitle`    | `string`                                                                                                                                                                                              |
| › `klevuCategory`    | `string`                                                                                                                                                                                              |
| › `override?`        | `Partial`\<`KlevuV1CategoryProductsClick`>                                                                                                                                                            |
| › `product`          | `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`> & `Partial`\<`Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"name"` \| `"itemGroupId"` \| `"salePrice"` \| `"sku"` \| `"url"`>> |
| › `productPosition?` | `number`                                                                                                                                                                                              |
| › `variantId?`       | `string`                                                                                                                                                                                              |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:368](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L368)

***

### categoryMerchandisingView

▸ `Static` **categoryMerchandisingView**(`«destructured»`): `void`

### Parameters

| Name                 | Type                                                             |
| -------------------- | ---------------------------------------------------------------- |
| `«destructured»`     | `Object`                                                         |
| › `abTestId?`        | `string`                                                         |
| › `abTestVariantId?` | `string`                                                         |
| › `activeFilters?`   | `string`                                                         |
| › `categoryTitle`    | `string`                                                         |
| › `klevuCategory`    | `string`                                                         |
| › `override?`        | `Partial`\<`KlevuV1CategoryProductsView`>                        |
| › `pageStartsFrom?`  | `number`                                                         |
| › `products`         | `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`>\[] |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:323](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L323)

***

### imageBannerClick

▸ `Static` **imageBannerClick**(`«destructured»`): `void`

When user clicks on the banner that is in quicksearch or on search landing page

### Parameters

| Name             | Type                                  | Description                         |
| ---------------- | ------------------------------------- | ----------------------------------- |
| `«destructured»` | `Object`                              | -                                   |
| › `bannerId`     | `string`                              | Id of the banner                    |
| › `bannerName`   | `string`                              | Name of the banner                  |
| › `imageUrl`     | `string`                              | Url of the image                    |
| › `override`     | `Partial`\<`KlevuV1ImageBannerClick`> | -                                   |
| › `targetUrl`    | `string`                              | Url where the user is redirected    |
| › `term`         | `string`                              | Search term used to get the results |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:423](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L423)

***

### recommendationClick

▸ `Static` **recommendationClick**(`«destructured»`): `void`

When product has been clicked in the recommendation banner

### Parameters

| Name                                        | Type                                                                                                                                                                                                                         | Description                        |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `«destructured»`                            | `Object`                                                                                                                                                                                                                     | -                                  |
| › `bannerInfo?`                             | `KlevuEventV2DataStaticContent`                                                                                                                                                                                              | -                                  |
| › `override?`                               | `Partial`\<`KlevuRecommendationsEventV2Data`>                                                                                                                                                                                | -                                  |
| › `product?`                                | `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`> & `Partial`\<`Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"name"` \| `"brand"` \| `"category"` \| `"currency"` \| `"itemGroupId"` \| `"salePrice"`>> | -                                  |
| › `productIndexInList?`                     | `number`                                                                                                                                                                                                                     | -                                  |
| › `recommendationMetadata`                  | `Object`                                                                                                                                                                                                                     | -                                  |
| › `recommendationMetadata.action?`          | `null` \| `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"`                                                                                                                                                        | Special cases of recommendation    |
| › `recommendationMetadata.enabled`          | `boolean`                                                                                                                                                                                                                    | -                                  |
| › `recommendationMetadata.logic`            | [`KMCRecommendationLogic`](docId\:z3h8LSdVbCGyAsT03bdBe)                                                                                                                                                                     | Logic used in recommendation       |
| › `recommendationMetadata.maxProducts`      | `number`                                                                                                                                                                                                                     | Amount of products to fetch        |
| › `recommendationMetadata.pageType`         | `KMCRecommendationPagetype`                                                                                                                                                                                                  | Target page type of recommendation |
| › `recommendationMetadata.productThreshold` | `number`                                                                                                                                                                                                                     | -                                  |
| › `recommendationMetadata.recsKey`          | `string`                                                                                                                                                                                                                     | ID of the recommendation           |
| › `recommendationMetadata.segmentKey`       | `null` \| `string`                                                                                                                                                                                                           | User segment key                   |
| › `recommendationMetadata.segmentName`      | `null` \| `string`                                                                                                                                                                                                           | User segment name                  |
| › `recommendationMetadata.spotKey`          | `string`                                                                                                                                                                                                                     | ID of the spot                     |
| › `recommendationMetadata.spotName`         | `string`                                                                                                                                                                                                                     | Spot name                          |
| › `recommendationMetadata.title`            | `string`                                                                                                                                                                                                                     | Title of the recommendation        |
| › `variantId?`                              | `string`                                                                                                                                                                                                                     | -                                  |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:170](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L170)

***

### recommendationView

▸ `Static` **recommendationView**(`«destructured»`): `void`

When recommendation banner is shown in the page

### Parameters

| Name                       | Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `«destructured»`           | `Object`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| › `override?`              | `Partial`\<`KlevuRecommendationsEventV2Data`>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| › `products?`              | `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`> & `Partial`\<`Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"name"` \| `"brand"` \| `"category"` \| `"currency"` \| `"itemGroupId"` \| `"price"` \| `"variantId"`>>\[]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| › `recommendationMetadata` | `Partial`\<\{ `action?`: `null` \| `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` ; `enabled`: `boolean` ; `logic`: [`KMCRecommendationLogic`](docId\:z3h8LSdVbCGyAsT03bdBe) ; `maxProducts`: `number` ; `pageType`: `KMCRecommendationPagetype` ; `productThreshold`: `number` ; `recsKey`: `string` ; `segmentKey`: `null` \| `string` ; `segmentName`: `null` \| `string` ; `spotKey`: `string` ; `spotName`: `string` ; `title`: `string`  }> & `Pick`\<\{ `action?`: `null` \| `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` ; `enabled`: `boolean` ; `logic`: [`KMCRecommendationLogic`](docId\:z3h8LSdVbCGyAsT03bdBe) ; `maxProducts`: `number` ; `pageType`: `KMCRecommendationPagetype` ; `productThreshold`: `number` ; `recsKey`: `string` ; `segmentKey`: `null` \| `string` ; `segmentName`: `null` \| `string` ; `spotKey`: `string` ; `spotName`: `string` ; `title`: `string`  }, `"logic"` \| `"recsKey"` \| `"title"`> |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:97](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L97)

***

### search

▸ `Static` **search**(`«destructured»`): `void`

What user has last searched. This is important for Klevu to function
properly. Use `sendSearchEvent()` modifier with search query to send results

### Parameters

| Name               | Type                                               |
| ------------------ | -------------------------------------------------- |
| `«destructured»`   | `Object`                                           |
| › `activeFilters?` | `string`                                           |
| › `override?`      | `Partial`\<`V1SearchEvent`>                        |
| › `term`           | `string`                                           |
| › `totalResults`   | `number`                                           |
| › `typeOfSearch`   | [`KlevuTypeOfSearch`](docId:3FsfdwGnKdoXmw8Q6AiU3) |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:284](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L284)

***

### searchProductClick

▸ `Static` **searchProductClick**(`«destructured»`): `void`

When product is clicked. Do not use this for recommendations

### Parameters

| Name               | Type                                                                                                                                                                      |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `«destructured»`   | `Object`                                                                                                                                                                  |
| › `activeFilters?` | `string`                                                                                                                                                                  |
| › `override?`      | `Partial`\<`V1ProductTrackingEvent`>                                                                                                                                      |
| › `product`        | `Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"id"`> & `Partial`\<`Pick`\<[`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly), `"name"` \| `"itemGroupId"` \| `"url"`>> |
| › `searchTerm?`    | `string`                                                                                                                                                                  |
| › `variantId?`     | `string`                                                                                                                                                                  |

### Returns

`void`

### Defined in

[events/KlevuEvents.ts:240](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L240)

[title] Class: KlevuResponseQueryObject
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuResponseQueryObject

Result object for each query. A storage for results. Can be used to fetch more data, send events etc.

## Table of contents

### Constructors

- [constructor](docId\:PhrCdX6tN6MMUtKZfUWjb)

### Properties

- [categoryMerchandisingClickEvent](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [func](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [getRedirects](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [hooks](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [query](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [recommendationBannerClickEvent](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [recommendationClickEvent](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [responseObject](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [searchClickEvent](docId\:PhrCdX6tN6MMUtKZfUWjb)

### Accessors

- [filters](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [functionParams](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [id](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [meta](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [records](docId\:PhrCdX6tN6MMUtKZfUWjb)

### Methods

- [#initEventFunctions](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [#initRedirects](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [annotationsById](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [getBanners](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [getPage](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [getQueryParameters](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [getTotalPages](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [hasNextPage](docId\:PhrCdX6tN6MMUtKZfUWjb)

## Constructors

### constructor

• **new KlevuResponseQueryObject**(`responseObject`, `query`, `func`)

### Parameters

| Name             | Type                                                           |
| ---------------- | -------------------------------------------------------------- |
| `responseObject` | [`KlevuResponseObject`](docId:_OzqIexf73M6LaMIC6_Oo)           |
| `query`          | [`KlevuQueryResult`](docId:7vdpEs-8-0Tv_43dyA7ly)              |
| `func`           | [`KlevuFetchFunctionReturnValue`](docId:7vdpEs-8-0Tv_43dyA7ly) |

### Defined in

[connection/responseQueryObject.ts:65](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L65)

## Properties

### categoryMerchandisingClickEvent

• `Optional` **categoryMerchandisingClickEvent**: (`params`: \{ `categoryTitle`: `string` ; `override?`: `Partial`\<`KlevuV1CategoryProductsView`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void`

### Type declaration

▸ (`params`): `void`

When query is categoryMerchandising this is available. It is used to send categoryMerchandising click events

### Parameters

| Name                   | Type                                      |
| ---------------------- | ----------------------------------------- |
| `params`               | `Object`                                  |
| `params.categoryTitle` | `string`                                  |
| `params.override?`     | `Partial`\<`KlevuV1CategoryProductsView`> |
| `params.productId`     | `string`                                  |
| `params.variantId?`    | `string`                                  |

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:48](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L48)

***

### func

• **func**: [`KlevuFetchFunctionReturnValue`](docId:7vdpEs-8-0Tv_43dyA7ly)

Function used to create this query

### Defined in

[connection/responseQueryObject.ts:33](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L33)

***

### getRedirects

• `Optional` **getRedirects**: () => `Promise`\<[`KlevuKeywordUrlMap`](docId\:LDP3zBw_oYVJHpfR0D2hy)\[]>

### Type declaration

▸ (): `Promise`\<[`KlevuKeywordUrlMap`](docId\:LDP3zBw_oYVJHpfR0D2hy)\[]>

Fetches redirects for this query. This is available only for search queries

### Returns

`Promise`\<[`KlevuKeywordUrlMap`](docId\:LDP3zBw_oYVJHpfR0D2hy)\[]>

### Defined in

[connection/responseQueryObject.ts:63](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L63)

***

### hooks

• **hooks**: [`KlevuResultEventOnResult`](docId:7vdpEs-8-0Tv_43dyA7ly)\[] = `[]`

Hooks that can be used to listen for events

### Defined in

[connection/responseQueryObject.ts:38](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L38)

***

### query

• **query**: [`KlevuQueryResult`](docId:7vdpEs-8-0Tv_43dyA7ly)

This query

### Defined in

[connection/responseQueryObject.ts:28](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L28)

***

### recommendationBannerClickEvent

• `Optional` **recommendationBannerClickEvent**: (`params`: \{ `resolution`: `"desktop"` | `"mobile"`  }) => `void`

### Type declaration

▸ (`params`): `void`

When there is a banner in the recommendation this is available. It is used to send recommendation banner click events

### Parameters

| Name                | Type                      |
| ------------------- | ------------------------- |
| `params`            | `Object`                  |
| `params.resolution` | `"desktop"` \| `"mobile"` |

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L58)

***

### recommendationClickEvent

• `Optional` **recommendationClickEvent**: (`params`: \{ `override?`: `Partial`\<`KlevuRecommendationsEventV2Data`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void`

### Type declaration

▸ (`params`): `void`

When query is recommendation this is available. It is used to send recommendation click events

### Parameters

| Name                | Type                                          |
| ------------------- | --------------------------------------------- |
| `params`            | `Object`                                      |
| `params.override?`  | `Partial`\<`KlevuRecommendationsEventV2Data`> |
| `params.productId`  | `string`                                      |
| `params.variantId?` | `string`                                      |

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:53](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L53)

***

### responseObject

• **responseObject**: [`KlevuResponseObject`](docId:_OzqIexf73M6LaMIC6_Oo)

Original request response that includes all queries

### Defined in

[connection/responseQueryObject.ts:23](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L23)

***

### searchClickEvent

• `Optional` **searchClickEvent**: (`params`: \{ `autoSendViewEvent?`: `boolean` ; `override?`: `Partial`\<`V1SearchEvent`> ; `productId`: `string` ; `variantId?`: `string`  }) => `void`

### Type declaration

▸ (`params`): `void`

When query is search this is available. It is used to send search click events

### Parameters

| Name                        | Type                        |
| --------------------------- | --------------------------- |
| `params`                    | `Object`                    |
| `params.autoSendViewEvent?` | `boolean`                   |
| `params.override?`          | `Partial`\<`V1SearchEvent`> |
| `params.productId`          | `string`                    |
| `params.variantId?`         | `string`                    |

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:43](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L43)

## Accessors

### filters

• `get` **filters**(): `undefined` | ([`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) | [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) | [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly))\[]

All filters related to this query

### Returns

`undefined` | ([`KlevuFilterResultOptions`](docId:7vdpEs-8-0Tv_43dyA7ly) | [`KlevuFilterResultSlider`](docId:7vdpEs-8-0Tv_43dyA7ly) | [`KlevuFilterResultRating`](docId:7vdpEs-8-0Tv_43dyA7ly))\[]

### Defined in

[connection/responseQueryObject.ts:80](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L80)

***

### functionParams

• `get` **functionParams**(): `undefined` | [`KlevuFetchFunctionParams`](docId:7vdpEs-8-0Tv_43dyA7ly)

Special parameters that are saved to query

### Returns

`undefined` | [`KlevuFetchFunctionParams`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Defined in

[connection/responseQueryObject.ts:108](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L108)

***

### id

• `get` **id**(): `string`

Id if the query

### Returns

`string`

### Defined in

[connection/responseQueryObject.ts:87](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L87)

***

### meta

• `get` **meta**(): `Object`

Meta data of the query

### Returns

`Object`

| Name                       | Type                                               | Description                                                                                                                                                                                                 |
| -------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`                   | `string`                                           | Klevu API key                                                                                                                                                                                               |
| `debuggingInformation`     | `unknown`                                          | Information that can be useful for debugging the query. For example, the actual query that was fired by the Klevu Search engine, inclusive of any synonyms or de-compounded words taken into consideration. |
| `isPersonalised`           | `boolean`                                          | -                                                                                                                                                                                                           |
| `klevuImageData?`          | \{ `processed`: \{ `urls`: `string`\[]  }\[]  }    | The urls processed in case of image search                                                                                                                                                                  |
| `klevuImageData.processed` | \{ `urls`: `string`\[]  }\[]                       | -                                                                                                                                                                                                           |
| `noOfResults`              | `number`                                           | The number of results requested to be returned for this query.                                                                                                                                              |
| `notificationCode`         | `number`                                           | This may be populated with a code if any actions were taken on the record. Possible values are: 1: Nothing to report. 2: The price of the record is using the base currency.                                |
| `offset`                   | `number`                                           | The index of the first result returned in this response.                                                                                                                                                    |
| `qTime`                    | `number`                                           | The time taken by the Klevu Search engine to fetch the response.                                                                                                                                            |
| `searchedTerm`             | `string`                                           | The search term submitted for this query.                                                                                                                                                                   |
| `totalResultsFound`        | `number`                                           | The total number of results found for this query.                                                                                                                                                           |
| `typeOfSearch`             | [`KlevuTypeOfSearch`](docId:3FsfdwGnKdoXmw8Q6AiU3) | The query type that was executed by Klevu to retrieve the results.                                                                                                                                          |

### Defined in

[connection/responseQueryObject.ts:94](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L94)

***

### records

• `get` **records**(): \{ `id`: `string`  } & [`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

Records of the query

### Returns

\{ `id`: `string`  } & [`KlevuRecord`](docId:7vdpEs-8-0Tv_43dyA7ly)\[]

### Defined in

[connection/responseQueryObject.ts:101](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L101)

## Methods

### #initEventFunctions

▸ `Private` **#initEventFunctions**(): `void`

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:206](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L206)

***

### #initRedirects

▸ `Private` **#initRedirects**(): `void`

### Returns

`void`

### Defined in

[connection/responseQueryObject.ts:194](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L194)

***

### annotationsById

▸ **annotationsById**(`productId`, `languageCode`): `Promise`\<`undefined` | [`KlevuAnnotations`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Parameters

| Name           | Type     |
| -------------- | -------- |
| `productId`    | `string` |
| `languageCode` | `string` |

### Returns

`Promise`\<`undefined` | [`KlevuAnnotations`](docId:7vdpEs-8-0Tv_43dyA7ly)>

### Defined in

[connection/responseQueryObject.ts:400](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L400)

***

### getBanners

▸ **getBanners**(`params?`): `Promise`\<[`KlevuBanner`](docId\:X1iaoTAGACK9B1KTwA3Io)\[]>

### Parameters

| Name                 | Type                               | Description                                                    |
| -------------------- | ---------------------------------- | -------------------------------------------------------------- |
| `params`             | `Object`                           | in case of search query you need to specify location of search |
| `params.searchType?` | `"landingpage"` \| `"quicksearch"` | -                                                              |

### Returns

`Promise`\<[`KlevuBanner`](docId\:X1iaoTAGACK9B1KTwA3Io)\[]>

List of banners that were received for this query

### Defined in

[connection/responseQueryObject.ts:408](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L408)

***

### getPage

▸ **getPage**(`params?`): `Promise`\<`undefined` | [`KlevuResponseObject`](docId:_OzqIexf73M6LaMIC6_Oo)>

Fetches page of results. If pageIndex is not defined it will fetch next page.

### Parameters

| Name                    | Type                                            | Description                                                                                              |
| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `params?`               | `Object`                                        |                                                                                                          |
| `params.filterManager?` | [`FilterManager`](docId\:ztQPUeYzosySERBcqiw4h) | Filter manager to apply for next function                                                                |
| `params.limit?`         | `number`                                        | Limit number of results for next query. By default this is automatically calculated from previous result |
| `params.pageIndex?`     | `number`                                        | Use page index to load certain page instead of next available. 0 is first page                           |

### Returns

`Promise`\<`undefined` | [`KlevuResponseObject`](docId:_OzqIexf73M6LaMIC6_Oo)>

### Defined in

[connection/responseQueryObject.ts:118](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L118)

***

### getQueryParameters

▸ **getQueryParameters**(): `undefined` | [`KlevuFetchFunctionParams`](docId:7vdpEs-8-0Tv_43dyA7ly)

### Returns

`undefined` | [`KlevuFetchFunctionParams`](docId:7vdpEs-8-0Tv_43dyA7ly)

List of params used in the query and the metadata that was generated during
the query. This is useful for example to fetching KMC metadata that was received
for recommendations query.

### Defined in

[connection/responseQueryObject.ts:421](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L421)

***

### getTotalPages

▸ **getTotalPages**(): `number`

### Returns

`number`

total number of pages

### Defined in

[connection/responseQueryObject.ts:190](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L190)

***

### hasNextPage

▸ **hasNextPage**(): `boolean`

### Returns

`boolean`

true if there are more pages to fetch

### Defined in

[connection/responseQueryObject.ts:179](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/responseQueryObject.ts#L179)

[title] Enumeration: KlevuTypeOfRequest
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuTypeOfRequest

## Table of contents

### Enumeration Members

- [AlsoBought](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [AlsoViewed](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [CategoryNavigation](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [Custom](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [NewArrivals](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [Search](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [SimilarProducts](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [Skip](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [Suggestion](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [Trending](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [VisuallySimilar](docId\:FbRj1Wkc03_boJHhtzdoQ)

## Enumeration Members

### AlsoBought

• **AlsoBought** = `"RECS_ALSO_BOUGHT"`

### Defined in

[models/KlevuTypeOfRequest.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L9)

***

### AlsoViewed

• **AlsoViewed** = `"RECS_ALSO_VIEWED"`

### Defined in

[models/KlevuTypeOfRequest.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L8)

***

### CategoryNavigation

• **CategoryNavigation** = `"CATNAV"`

### Defined in

[models/KlevuTypeOfRequest.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L4)

***

### Custom

• **Custom** = `"RECS_CUSTOM"`

### Defined in

[models/KlevuTypeOfRequest.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L11)

***

### NewArrivals

• **NewArrivals** = `"RECS_NEW_ARRIVALS"`

### Defined in

[models/KlevuTypeOfRequest.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L5)

***

### Search

• **Search** = `"SEARCH"`

### Defined in

[models/KlevuTypeOfRequest.ts:2](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L2)

***

### SimilarProducts

• **SimilarProducts** = `"RECS_SIMILAR"`

### Defined in

[models/KlevuTypeOfRequest.ts:6](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L6)

***

### Skip

• **Skip** = `"SKIP"`

### Defined in

[models/KlevuTypeOfRequest.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L13)

***

### Suggestion

• **Suggestion** = `"AUTO_SUGGESTIONS"`

### Defined in

[models/KlevuTypeOfRequest.ts:3](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L3)

***

### Trending

• **Trending** = `"RECS_TRENDING"`

### Defined in

[models/KlevuTypeOfRequest.ts:7](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L7)

***

### VisuallySimilar

• **VisuallySimilar** = `"RECS_SIMILAR_IMAGES"`

### Defined in

[models/KlevuTypeOfRequest.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRequest.ts#L10)

[title] Class: KlevuConfig
[path] Classes/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuConfig

## Table of contents

### Constructors

- [constructor](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Properties

- [apiKey](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [axios](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [cacheMaxTTL](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [disableClickTracking](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [eventsApiV1Url](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [eventsApiV2Url](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [moiApiUrl](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [recommendationsApiUrl](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [url](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [default](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Methods

- [getDefault](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [init](docId\:w2RkeCQV7dYsnPOEOFH1J)

## Constructors

### constructor

• **new KlevuConfig**(`config`)

### Parameters

| Name     | Type                 |
| -------- | -------------------- |
| `config` | `KlevuConfiguration` |

### Defined in

[config.ts:63](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L63)

## Properties

### apiKey

• **apiKey**: `string`

### Defined in

[config.ts:53](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L53)

***

### axios

• `Optional` **axios**: `AxiosInstance`

### Defined in

[config.ts:59](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L59)

***

### cacheMaxTTL

• **cacheMaxTTL**: `number` = `600_000`

### Defined in

[config.ts:55](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L55)

***

### disableClickTracking

• **disableClickTracking**: `boolean` = `false`

### Defined in

[config.ts:61](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L61)

***

### eventsApiV1Url

• **eventsApiV1Url**: `string` = `"https://stats.ksearchnet.com/analytics/"`

### Defined in

[config.ts:56](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L56)

***

### eventsApiV2Url

• **eventsApiV2Url**: `string` = `"https://stats.ksearchnet.com/analytics/collect"`

### Defined in

[config.ts:57](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L57)

***

### moiApiUrl

• **moiApiUrl**: `string` = `"https://moi-ai.ksearchnet.com/"`

### Defined in

[config.ts:60](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L60)

***

### recommendationsApiUrl

• **recommendationsApiUrl**: `string` = `"https://config-cdn.ksearchnet.com/recommendations/"`

### Defined in

[config.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L58)

***

### url

• **url**: `string`

### Defined in

[config.ts:54](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L54)

***

### default

▪ `Static` **default**: `undefined` | [`KlevuConfig`](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Defined in

[config.ts:51](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L51)

## Methods

### getDefault

▸ `Static` **getDefault**(): [`KlevuConfig`](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Returns

[`KlevuConfig`](docId\:w2RkeCQV7dYsnPOEOFH1J)

### Defined in

[config.ts:93](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L93)

***

### init

▸ `Static` **init**(`config`): `void`

### Parameters

| Name     | Type                 |
| -------- | -------------------- |
| `config` | `KlevuConfiguration` |

### Returns

`void`

### Defined in

[config.ts:88](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/config.ts#L88)

[title] imagesearch
[path] Modules/

▸ **imageSearch**(`image`, `options?`, `...modifiers`): `Promise`\<[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)>

Uploads the image if blob passed or uses url to perform search



Error when image upload fails or when no url/blob is passed

### Parameters

| Name           | Type                                                             | Description                                        |
| -------------- | ---------------------------------------------------------------- | -------------------------------------------------- |
| `image`        | `string` \| `Blob`                                               | Pass a url or the image blob for search            |
| `options?`     | `Partial`\<[`KlevuSearchOptions`](docId\:oPnz3pXXIAZwE9oJVUONX)> | [KlevuSearchOptions](docId\:oPnz3pXXIAZwE9oJVUONX) |
| `...modifiers` | `KlevuFetchModifer`\[]                                           | -                                                  |

### Returns

`Promise`\<[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)>

### Defined in

[queries/imageSearch/imageSearch.ts:18](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/imageSearch/imageSearch.ts#L18)

[title] klevualsoboughtquery
[path] Modules/

Ƭ **KlevuAlsoBoughtQuery**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) & [`KlevuAlsoViewedQuery`](docId\:ITcsCHsRNvvCZ6MaPonoG) & \{ `typeOfRequest`: [`AlsoBought`](enums/KlevuTypeOfRequest.md#alsobought)  }

Backend API parameters relevat for Also Bought Recommendation query

### Defined in

[models/KlevuAlsoBoughtQuery.ts:8](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuAlsoBoughtQuery.ts#L8)

[title] klevusimilarproductsquery
[path] Modules/

Ƭ **KlevuSimilarProductsQuery**: [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) & \{ `settings`: \{ `context`: \{ `recentObjects`: \{ `records`: \{ `id`: `string`  }\[] ; `typeOfRecord`: [`KlevuAnyTypeOfRecord`](docId\:ktm5WqTo44NqfuwUMTxje)  }\[]  }  } ; `typeOfRequest`: [`SimilarProducts`](enums/KlevuTypeOfRequest.md#similarproducts)  }

### Defined in

[models/KlevuSimilarProductsQuery.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuSimilarProductsQuery.ts#L4)

[title] klevuanytypeofrecord
[path] Modules/

Ƭ **KlevuAnyTypeOfRecord**: `LiteralUnion`\<`ValueOf`\<typeof [`KlevuTypeOfRecord`](enums/KlevuTypeOfRecord.md)>, `string`>

### Defined in

[models/KlevuTypeOfRecord.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuTypeOfRecord.ts#L11)

[title] klevuhydratepackedfetchresult
[path] Modules/

▸ **KlevuHydratePackedFetchResult**(`packed`, `functions`): `Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

This function hydrates KlevuFetch response object from raw JSON that was fetched on server side.
It doesn't do request to Klevu API, but it will do requests that are made with logic of queries.
For example all analytical requests are automatically sent from client.

### Parameters

| Name        | Type                                                  | Description                                                 |
| ----------- | ----------------------------------------------------- | ----------------------------------------------------------- |
| `packed`    | [`KlevuApiRawResponse`](docId\:OuLSbkYPK2-rGgqH6qeog) | Raw JSON from KlevuFetch                                    |
| `functions` | [`KlevuFetchQueries`](docId\:q5OZXYWoRdA58lqyW-VbL)   | Query functions used to create KlevuFetch query in backend. |

### Returns

`Promise`\<[`KlevuResponseObject`](classes/KlevuResponseObject.md)>

KlevuFetch response without making any request to servers

### Defined in

[connection/hydration.ts:30](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/hydration.ts#L30)

[title] klevufallbackqueryoptions
[path] Modules/

Ƭ **KlevuFallbackQueryOptions**: `Object`

### Type declaration

| Name                     | Type     |
| ------------------------ | -------- |
| `runWhenLessThanResults` | `number` |

### Defined in

[modifiers/fallback/fallback.ts:5](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/fallback/fallback.ts#L5)

[title] applyfilters
[path] Modules/

▸ **applyFilters**(`filters`): `KlevuFetchModifer`

### Parameters

| Name      | Type                                            |
| --------- | ----------------------------------------------- |
| `filters` | [`ApplyFilter`](docId:9FRwRaGZKc4DqRPsJpLO0)\[] |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/applyFilter/applyFilter.ts:21](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/applyFilter/applyFilter.ts#L21)

[title] klevumerchandisingoptions
[path] Modules/

Ƭ **KlevuMerchandisingOptions**: \{ `id`: `string` ; `searchTerm`: `string`  } & `Omit`\<[`KlevuBaseQuerySettings`](docId\:DyD-sdD9prRQ0gcOerUbZ), `"query"`>

### Defined in

[queries/categoryMerchandising/categoryMerchandising.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/categoryMerchandising/categoryMerchandising.ts#L10)

[title] moilocalmessage
[path] Modules/

Ƭ **MoiLocalMessage**: `Object`

### Type declaration

| Name            | Type                      |
| --------------- | ------------------------- |
| `local`         | \{ `message`: `string`  } |
| `local.message` | `string`                  |

### Defined in

[connection/moi/moi.ts:142](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L142)

[title] debug
[path] Modules/

▸ **debug**(): `KlevuFetchModifer`

Prints queries to console for easier debugging

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/debug/debug.ts:9](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/debug/debug.ts#L9)

[title] klevulistfilter
[path] Modules/

Ƭ **KlevuListFilter**: `Object`

### Type declaration

| Name               | Type                                                       |
| ------------------ | ---------------------------------------------------------- |
| `filtersToReturn?` | [`KlevuListFiltersToReturn`](docId\:f3xhbsbg56soFg-zEvZbF) |

### Defined in

[models/KlevuListFilter.ts:55](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuListFilter.ts#L55)

[title] include
[path] Modules/

▸ **include**(`ids`): `KlevuFetchModifer`

Force include product ids on result

### Parameters

| Name  | Type        |
| ----- | ----------- |
| `ids` | `string`\[] |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/include/include.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/include/include.ts#L10)

[title] klevuapplyfilter
[path] Modules/

Ƭ **KlevuApplyFilter**: `Object`

Apply Filter type for Klevu base query

### Type declaration

| Name                   | Type                                                                                                                                      |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `applyFilters?`        | \{ `filters`: \{ `key`: `string` ; `settings?`: \{ `singleSelect`: `boolean`  } ; `values`: `string`\[] \| \[`number`, `number`]  }\[]  } |
| `applyFilters.filters` | \{ `key`: `string` ; `settings?`: \{ `singleSelect`: `boolean`  } ; `values`: `string`\[] \| \[`number`, `number`]  }\[]                  |

### Defined in

[models/KlevuApplyFilter.ts:4](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApplyFilter.ts#L4)

[title] abtest
[path] Modules/

▸ **abTest**(): `KlevuFetchModifer`

Enables AB test functionality. This will make extra request to Klevu servers and it is recommended only if you wish to use A/B testing feature.

Currently not supported in server side rendering.

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/abTest/abTest.ts:20](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/abTest/abTest.ts#L20)

[title] klevufetchqueries
[path] Modules/

Ƭ **KlevuFetchQueries**: (`Promise`\<[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)> | [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito))\[]

### Defined in

[models/KlevuFetchQueries.ts:3](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuFetchQueries.ts#L3)

[title] klaviyo
[path] Modules/

▸ **klaviyo**(`params?`): `KlevuFetchModifer`

Automatically sends search event to Klaviyo on search, recommendations and category navigation.

### Parameters

| Name     | Type             |
| -------- | ---------------- |
| `params` | `KlaviyoOptions` |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/klaviyo/klaviyo.ts:22](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/klaviyo/klaviyo.ts#L22)

[title] klevufilterresultslider
[path] Modules/

Ƭ **KlevuFilterResultSlider**: `KlevuFilterResult` & \{ `end`: `string` | `null` ; `max`: `string` ; `min`: `string` ; `start`: `string` | `null` ; `type`: [`Slider`](enums/KlevuFilterType.md#slider)  }

Klevu slider filters

### Defined in

[models/KlevuApiRawResponse.ts:59](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuApiRawResponse.ts#L59)

[title] klevulastclickedproducts
[path] Modules/

• `Const` **KlevuLastClickedProducts**: `LastClickedProducts`

### Defined in

[store/lastClickedProducts.ts:153](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/lastClickedProducts.ts#L153)

[title] Interface: KMCBannerRootObject
[path] Interfaces/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KMCBannerRootObject

## Table of contents

### Properties

- [klevu\_banner](docId\:TlnWi6pTUeoNh7F2XuuCs)

## Properties

### klevu\_banner

• **klevu\_banner**: [`KlevuBanner`](docId\:X1iaoTAGACK9B1KTwA3Io)\[]

### Defined in

[models/KMCBanner.ts:21](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCBanner.ts#L21)

[title] Interface: KlevuKeywordUrlMap
[path] Interfaces/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / KlevuKeywordUrlMap

## Table of contents

### Properties

- [keywords](docId\:LDP3zBw_oYVJHpfR0D2hy)
- [url](docId\:LDP3zBw_oYVJHpfR0D2hy)

## Properties

### keywords

• **keywords**: `string`\[]

### Defined in

[models/KMCMaps.ts:2](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCMaps.ts#L2)

***

### url

• **url**: `string`

### Defined in

[models/KMCMaps.ts:3](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KMCMaps.ts#L3)

[title] boostwithkeywords
[path] Modules/

▸ **boostWithKeywords**(`keywords`): `KlevuFetchModifer`

Boost or deboost query based on a keywords.

### Parameters

| Name       | Type                                             | Description                   |
| ---------- | ------------------------------------------------ | ----------------------------- |
| `keywords` | \{ `phrase`: `string` ; `weight`: `number`  }\[] | Keywords to boost and deboost |

### Returns

`KlevuFetchModifer`

KlevuModifier that be used to modify query

### Defined in

[modifiers/boostWithKeywords/boostWithKeywords.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/boostWithKeywords/boostWithKeywords.ts#L10)

[title] Enumeration: AdvancedSortingDiretion
[path] Enums/

 / [Exports](docId:7vdpEs-8-0Tv_43dyA7ly) / AdvancedSortingDiretion

## Table of contents

### Enumeration Members

- [Ascending](docId\:vNXwGv9ESAHIY5Cl_6aJ8)
- [Descending](docId\:vNXwGv9ESAHIY5Cl_6aJ8)

## Enumeration Members

### Ascending

• **Ascending** = `"ASC"`

### Defined in

[models/KlevuBaseQuerySettings.ts:286](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuBaseQuerySettings.ts#L286)

***

### Descending

• **Descending** = `"DESC"`

### Defined in

[models/KlevuBaseQuerySettings.ts:287](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuBaseQuerySettings.ts#L287)

[title] klevuresulteventonresult
[path] Modules/

Ƭ **KlevuResultEventOnResult**: (`params`: \{ `productId`: `string` ; `type`: `"search"` | `"categoryMerchandising"` | `"recommendation"` ; `variantId?`: `string`  }) => `Promise`\<`void`>

### Type declaration

▸ (`params`): `Promise`\<`void`>

### Parameters

| Name                | Type                                                          |
| ------------------- | ------------------------------------------------------------- |
| `params`            | `Object`                                                      |
| `params.productId`  | `string`                                                      |
| `params.type`       | `"search"` \| `"categoryMerchandising"` \| `"recommendation"` |
| `params.variantId?` | `string`                                                      |

### Returns

`Promise`\<`void`>

### Defined in

[models/KlevuResultEvent.ts:45](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/models/KlevuResultEvent.ts#L45)

[title] advancedsorting
[path] Modules/

▸ **advancedSorting**(`sorts`): `KlevuFetchModifer`

Set advanced sorting to request.
Does not apply if sort is something else than AdvancedSort or undefined.

### Parameters

| Name    | Type                                                                                                                                 | Description                           |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
| `sorts` | `undefined` \| \{ `key`: `string` ; `order`: [`AdvancedSortingDiretion`](enums/AdvancedSortingDiretion.md) ; `type`: `"FIELD"`  }\[] | Array of sorts to apply to the query. |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/advancedSorting/advancedSorting.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/advancedSorting/advancedSorting.ts#L13)

[title] raw
[path] Modules/

▸ **raw**(`query`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Take control and write any kind of query you wish to Klevu API. For experts only.

### Parameters

| Name           | Type                                             |
| -------------- | ------------------------------------------------ |
| `query`        | [`KlevuBaseQuery`](docId\:f12W_nXKSdxhmQbguOtp5) |
| `...modifiers` | `KlevuFetchModifer`\[]                           |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/raw/raw.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/raw/raw.ts#L13)

[title] newarrivals
[path] Modules/

▸ **newArrivals**(`category?`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Get new arrival recommendations

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `category?`    | `string`               |
| `options?`     | `Partial`\<`Options`>  |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/newarrivals/newarrivals.ts:21](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/newarrivals/newarrivals.ts#L21)

[title] moirequest
[path] Modules/

Ƭ **MoiRequest**: `Object`

### Type declaration

| Name                  | Type                                                                              |
| --------------------- | --------------------------------------------------------------------------------- |
| `context`             | [`MoiContext`](docId\:kIYizzef1kgLJcSqoO9pI)                                      |
| `feedback?`           | \{ `messageId`: `string` ; `reason?`: `string` ; `thumbs?`: `"UP"` \| `"DOWN"`  } |
| `feedback.messageId`  | `string`                                                                          |
| `feedback.reason?`    | `string`                                                                          |
| `feedback.thumbs?`    | `"UP"` \| `"DOWN"`                                                                |
| `filter?`             | \{ `value`: `string`  }                                                           |
| `filter.value`        | `string`                                                                          |
| `klevuSettings?`      | `Omit`\<[`KlevuBaseQuerySettings`](docId\:DyD-sdD9prRQ0gcOerUbZ), `"query"`>      |
| `message?`            | `string`                                                                          |
| `product?`            | \{ `context`: \{ `url`: `string`  } ; `id`: `string` ; `intent`: `string`  }      |
| `product.context`     | \{ `url`: `string`  }                                                             |
| `product.context.url` | `string`                                                                          |
| `product.id`          | `string`                                                                          |
| `product.intent`      | `string`                                                                          |

### Defined in

[connection/moi/moi.ts:19](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L19)

[title] @klevu/core
[path] /

 / Exports

## Table of contents

### KlevuEvents

Global custom document events that @klevu/core sends Enumerations

- [KlevuDomEvents](docId\:NobpYQt4aZ1JcaHPTNcMB)

### Other Enumerations

- [AdvancedSortingDiretion](docId\:vNXwGv9ESAHIY5Cl_6aJ8)
- [KMCRecommendationLogic](docId\:z3h8LSdVbCGyAsT03bdBe)
- [KlevuFilterOrder](docId\:u25KG78OsvzaBbN999cTI)
- [KlevuFilterType](docId\:WW8-Ksa2-cuoaIcKix5tp)
- [KlevuSearchPreference](docId:4CSizq9eos8dHPK21r01b)
- [KlevuSearchSorting](docId\:RX8X6NC9hFqbDTOXiITMz)
- [KlevuTypeOfRecord](docId\:vONWNcusXpLJmZ_Ae8_9Y)
- [KlevuTypeOfRequest](docId\:FbRj1Wkc03_boJHhtzdoQ)
- [KlevuTypeOfSearch](docId:3FsfdwGnKdoXmw8Q6AiU3)

### KlevuEvents Classes

- [KlevuEvents](docId\:v4S0tEBONPr8hwup9X7dW)

### Other Classes

- [FilterManager](docId\:ztQPUeYzosySERBcqiw4h)
- [KlevuConfig](docId\:w2RkeCQV7dYsnPOEOFH1J)
- [KlevuResponseObject](docId:_OzqIexf73M6LaMIC6_Oo)
- [KlevuResponseQueryObject](docId\:PhrCdX6tN6MMUtKZfUWjb)
- [MoiSession](docId\:VI7zz0Y-gAkL5higBbVZ3)

### Interfaces

- [KMCBannerRootObject](docId\:TlnWi6pTUeoNh7F2XuuCs)
- [KMCMapsRootObject](docId\:wbf7MpBATi9iiAy9R5uP3)
- [KMCRootObject](docId\:cmyvmblfFvreTWOW6tgAd)
- [KlevuBanner](docId\:X1iaoTAGACK9B1KTwA3Io)
- [KlevuKeywordUrlMap](docId\:LDP3zBw_oYVJHpfR0D2hy)

### Type Aliases

- [ApplyFilter](docId:9FRwRaGZKc4DqRPsJpLO0)
- [FilterManagerFilters](docId\:JNvd4KD1QwTYk6-cjPYZL)
- [KlevuAllRecordQueries](docId\:aemJGcPHnPvj5gp7OE6gs)
- [KlevuAlsoBoughtQuery](docId\:gjuq8L5rnfCixr5xjQsHa)
- [KlevuAlsoViewedQuery](docId\:ITcsCHsRNvvCZ6MaPonoG)
- [KlevuAnnotations](docId\:ZM_n2M_w_iJJQ8wX2wffJ)
- [KlevuAnyTypeOfRecord](docId\:ktm5WqTo44NqfuwUMTxje)
- [KlevuApiRawResponse](docId\:OuLSbkYPK2-rGgqH6qeog)
- [KlevuApplyFilter](docId:18mjL60ULCGi9EQEYq1In)
- [KlevuBaseQuery](docId\:f12W_nXKSdxhmQbguOtp5)
- [KlevuBaseQuerySettings](docId\:DyD-sdD9prRQ0gcOerUbZ)
- [KlevuBaseQuerySettingsQuery](docId\:h8sc81d2rTm9HYUndahZN)
- [KlevuFallbackQueryOptions](docId:-fi6i8IwD3C5-UZbn4THv)
- [KlevuFetchFunctionParams](docId\:SykuVchrFw4dLCH2nmQ8k)
- [KlevuFetchFunctionReturnValue](docId\:T803lqj3C91t_7d1wZito)
- [KlevuFetchQueries](docId\:q5OZXYWoRdA58lqyW-VbL)
- [KlevuFetchQueryResult](docId\:GqGhGYiSs2VhANdvEPM_9)
- [KlevuFetchResponse](docId\:VI5JRTKTZCm6Sdx7F7IGq)
- [KlevuFilterResultOptions](docId\:FNVkZmp1dfTp_h3p4eBVz)
- [KlevuFilterResultRating](docId\:SHCU6ypFRKJloKIC1ArIw)
- [KlevuFilterResultSlider](docId\:zKpvQRhNOp9EevKLWczEn)
- [KlevuKMCRecommendationOptions](docId:-_5sVna_LGb9MuD61lV08)
- [KlevuKMCRecommendations](docId\:Vo7OtiF0AXpgHUYvWUVrl)
- [KlevuLastSearch](docId\:Wh31YKMY8igOGvQBPC7Hh)
- [KlevuListFilter](docId:2o3vpdB6dnUslrPgAIaCs)
- [KlevuListFiltersToReturn](docId\:f3xhbsbg56soFg-zEvZbF)
- [KlevuMerchandisingOptions](docId\:Wa_CuGIog7wxiYPZYOrgu)
- [KlevuNextFunc](docId\:uZrBd4V05dAaoVLNKRUmT)
- [KlevuPayload](docId\:FOJRevUwsN8FXfFxi3aHF)
- [KlevuQueryResult](docId\:CGLzKe0jhD8maf-Iy_RLX)
- [KlevuRangeFilterSettings](docId\:qEjqx8vypdhY8n1lpOGU-)
- [KlevuRecord](docId\:vA8Kz9WZX3r_nThlqQ1i4)
- [KlevuRecordFields](docId:0GJGfiUirmy4bKyBKAkqe)
- [KlevuResultEvent](docId\:tmZpXTl378r572rBXU5i5)
- [KlevuResultEventOnResult](docId\:ymHUuQ_gTYkxpo0aUpjSG)
- [KlevuSearchOptions](docId\:oPnz3pXXIAZwE9oJVUONX)
- [KlevuSimilarProductsQuery](docId:9TNwVNTU8sbBzqKIG2fKk)
- [KlevuSuggestionQuery](docId:1_-FvnZldotd6ffHFIrs5)
- [KlevuSuggestionResult](docId\:yQSz4WXRMGv61HqrbSwwi)
- [KlevuTrendingProductsQuery](docId\:Z-ji4NGdhse100C2uEAIw)
- [MoiActionsMessage](docId\:WrJO6fGuUG_px6-6W4o1Z)
- [MoiChatModes](docId\:emBLFzL6rES1tkprIbcb6)
- [MoiContext](docId\:kIYizzef1kgLJcSqoO9pI)
- [MoiLocalMessage](docId\:vMySWnBYqm_OowcAe4QGJ)
- [MoiMenuOptions](docId\:JAsD1cuAj7d5dLUuISAOR)
- [MoiMessages](docId\:Ds_88jfoYhH5JpBMTWueb)
- [MoiProduct](docId\:tIPkvF85xDft2BF930T5A)
- [MoiProducts](docId\:oVFUBTviQeo-zUbPC4M5W)
- [MoiRequest](docId\:wNx_wTuxa3J8uG0I_N_nr)
- [MoiResponse](docId\:FRgTZpcMcDaa4n8zIYKM4)
- [MoiResponseContext](docId\:y9i3RA_lBeg3ik0jpe68u)
- [MoiResponseFilter](docId:2_K2WkBpkWSaXYxOymHai)
- [MoiResponseGenericOptions](docId\:DMCLo2pR2oMPSRjoC44sL)
- [MoiResponseObjects](docId\:FkvPsZ7aGi4volRkw62Jw)
- [MoiResponseText](docId:9S37kRMdItq5Dsi4dr6zO)
- [MoiSavedFeedback](docId\:k1zPxdOhijvVD4l6LMJLa)
- [MoiStartOptions](docId\:lkD7d8i4M6XW1DxztVOQR)
- [RecommendationViewEventMetaData](docId\:ncLFMsJ5JpH1onJCiJdpD)

### Variables

- [KlevuLastClickedProducts](docId\:Z5YNyKCH5Nr2k1b_Zudvp)
- [KlevuLastSearches](docId\:g4sYJnehAtFH0kNMmAc_T)
- [klevuFetchCache](docId\:s3qN65XyJP0npWyEYk8J9)

### KlevuFetch Functions

- [KlevuFetch](docId\:qj7FySybJVkFVrUSc3-Ku)
- [KlevuKMCSettings](docId\:K9QPcRNqx_z43rfEkk0NK)

### RecommendationQuery Functions

- [alsoViewed](docId\:QX6nkThhtDzFQyW2VYBUE)
- [boughtTogether](docId\:b3__Ft363oJc3eEMweDaH)
- [kmcRecommendation](docId\:AslLCX73q9v1RcJaEXznM)
- [newArrivals](docId\:EU1P92GT2zH6IbXpcjVJ4)
- [recentlyViewed](docId\:HZnOnl50djtz6434TZ4hs)
- [searchCategory](docId\:V_G38mL1sOwtZAuhVO6Zj)
- [searchCms](docId\:aRNU8-2xD9HscppzV1XEt)
- [similarProducts](docId\:yxKf-q5s_dtc1qcXQcFWN)
- [trendingCategoryProducts](docId\:OjKwRfZ2eaP18sJReDiUj)
- [visuallySimilar](docId\:BSR-t8f_kvuqksKmFUDon)

### Modifier Functions

- [abTest](docId\:WZOkV4eqraR8CT9guH09l)
- [advancedFiltering](docId\:GvPmiQMIzlRyPf6STG10x)
- [advancedSorting](docId\:S2a35icbifq1WeNYqLDZw)
- [applyFilterWithManager](docId\:iyp6HZgLcfqxqoho7EO8J)
- [applyFilters](docId\:m_eg3IXE3hPsIgZWdt-yq)
- [boostWithFilterManager](docId\:ByweDER9e8zHQL1Wge0fa)
- [boostWithFilters](docId\:MeYQVsEP3giMbwb5w27nJ)
- [boostWithKeywords](docId\:wFLFQ089bYLl2QjuF26q3)
- [boostWithRecords](docId\:OTLI2ncPisiieBcFVLmHL)
- [debug](docId\:n5eb_d0sk-9md9DBOFiQi)
- [exclude](docId\:TkKC45mXQY_Hgtsq3ejdc)
- [fallback](docId\:JHw5ugZKu60JWtqucahrB)
- [include](docId:1j8vZ7eolIvqW5kMfeORB)
- [injectFilterResult](docId\:Sz1vHjwhloN32x2RhkZJy)
- [listFilters](docId\:e21WV4C3yLFWXOdvl_dfu)
- [overrideSettings](docId:5gO3qT-NIKK80G8VicMXm)
- [personalisation](docId:5t7FnTGNjc5j0sKFk0jdo)
- [sendMerchandisingViewEvent](docId\:aLRXUMMcmHc0tGSWI2f6T)
- [sendRecommendationViewEvent](docId\:AJR5Xhd3d480baVzmezx2)
- [sendSearchEvent](docId\:bHJ1-zaS_T61vJ8eBWavG)
- [top](docId:0nKOz-VW7gEztNs7BKSLv)

### KlevuEvents Functions

- [KlevuListenDomEvent](docId\:Bwjk9GskC2LF9MmQ6icL2)

### Other Functions

- [KlevuGetBannersByType](docId\:m0A6TIbV6GiKPxNtrgqqG)
- [KlevuHydratePackedFetchResult](docId\:LU8fosxFx2zV_nPVQ3Loq)
- [KlevuPackFetchResult](docId\:XRAHNQjQRbEqRnWQaZzKI)
- [KlevuUploadImageForSearch](docId\:k851EDtCkZ26po49x5nJG)
- [imageSearch](docId\:lrE7sDC15Z78KKjh0AgdN)
- [klaviyo](docId\:W65KnTXUXqpE4xd8VER_-)
- [removeListFilters](docId\:MZ3VnB0UxDS1wLxlWRpvs)
- [startMoi](docId\:gUaB_qZRJcpAx5-miD-DC)

### Query Functions

- [categoryMerchandising](docId\:HtmjubYV1j0fLJYu0XDQV)
- [products](docId\:ez68Xwue17asc--IPKDP4)
- [raw](docId\:s34QbUAihobUIQSiPZacq)
- [search](docId\:AtPkL6cEuhS9C8oYWZV6i)
- [suggestions](docId\:v-G_EFFgH_BZ3GQcfqG2J)
- [trendingProducts](docId\:GvP_AzqnuhzcVlk_ScweH)

[title] personalisation
[path] Modules/

▸ **personalisation**(`options?`): `KlevuFetchModifer`

Enable personlisation to the query

### Parameters

| Name                             | Type                                                  | Description                                                                                                                                                                                                                                                                                 |
| -------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `options?`                       | `Object`                                              |                                                                                                                                                                                                                                                                                             |
| `options.fields?`                | [`KlevuRecordFields`](docId:0GJGfiUirmy4bKyBKAkqe)\[] | This is an optional field. By default, Klevu will analyse all attributes of the records the customer has interacted with, in order to determine the common patterns. If you prefer to focus on particular aspects, for example brand or price, specify those attributes within this object. |
| `options.lastClickedProductIds?` | `string`\[]                                           | Override last clicked product id's with your own selection. First item should be the latest product clicked. By default @klevu/core uses internal store to keep track of last clicked products. It is important use KlevuEvent class to store all interactions.                             |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/personalisation/personalisation.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/personalisation/personalisation.ts#L12)

[title] sendmerchandisingviewevent
[path] Modules/

▸ **sendMerchandisingViewEvent**(`title`, `override?`): `KlevuFetchModifer`

This modifier should be used with merchandising query. It sends
automatically correct event data to Klevu

### Parameters

| Name        | Type                                      | Description                       |
| ----------- | ----------------------------------------- | --------------------------------- |
| `title`     | `string`                                  | Title of the category page viewed |
| `override?` | `Partial`\<`KlevuV1CategoryProductsView`> | -                                 |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/sendMerchandisingViewEvent/sendMerchandisingViewEvent.ts:14](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/sendMerchandisingViewEvent/sendMerchandisingViewEvent.ts#L14)

[title] removelistfilters
[path] Modules/

▸ **removeListFilters**(`f`, `prevQueryResult`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Removes list filters from query

### Parameters

| Name              | Type                                                            |
| ----------------- | --------------------------------------------------------------- |
| `f`               | [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito) |
| `prevQueryResult` | [`KlevuQueryResult`](docId\:CGLzKe0jhD8maf-Iy_RLX)              |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[connection/klevuFetch.ts:141](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/klevuFetch.ts#L141)

[title] searchcms
[path] Modules/

▸ **searchCms**(`term`, `options?`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Search helper function that sets correct settings

### Parameters

| Name       | Type                                                             | Description      |
| ---------- | ---------------------------------------------------------------- | ---------------- |
| `term`     | `string`                                                         | cms page to find |
| `options?` | `Partial`\<[`KlevuSearchOptions`](docId\:oPnz3pXXIAZwE9oJVUONX)> |                  |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/searchCms/searchCms.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/searchCms/searchCms.ts#L13)

[title] suggestions
[path] Modules/

▸ **suggestions**(`term`, `options?`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Return suggestion on given search term

### Parameters

| Name       | Type                  | Description |
| ---------- | --------------------- | ----------- |
| `term`     | `string`              | search term |
| `options?` | `Partial`\<`Options`> |             |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/suggestions/suggestions.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/suggestions/suggestions.ts#L24)

[title] trendingcategoryproducts
[path] Modules/

▸ **trendingCategoryProducts**(`categoryPath`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Return trending recommendations

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `categoryPath` | `string`               |
| `options?`     | `Partial`\<`Options`>  |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/trendingCategoryProducts/trendingCategoryProducts.ts:39](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/trendingCategoryProducts/trendingCategoryProducts.ts#L39)

[title] recentlyviewed
[path] Modules/

▸ **recentlyViewed**(`options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Recently viewed products

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `options?`     | `Partial`\<`Options`>  |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/recentlyViewedProducts/recentlyViewedProducts.ts:26](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/recentlyViewedProducts/recentlyViewedProducts.ts#L26)

[title] sendrecommendationviewevent
[path] Modules/

▸ **sendRecommendationViewEvent**(`eventData?`, `override?`): `KlevuFetchModifer`

This modifier should be used with all recommendation requests. It sends
correct event data to klevu backend on recommendation view

### Parameters

| Name         | Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `eventData?` | `Partial`\<\{ `action?`: `null` \| `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` ; `enabled`: `boolean` ; `logic`: [`KMCRecommendationLogic`](enums/KMCRecommendationLogic.md) ; `maxProducts`: `number` ; `pageType`: `KMCRecommendationPagetype` ; `productThreshold`: `number` ; `recsKey`: `string` ; `segmentKey`: `null` \| `string` ; `segmentName`: `null` \| `string` ; `spotKey`: `string` ; `spotName`: `string` ; `title`: `string`  }> & `Pick`\<\{ `action?`: `null` \| `"STATIC_CONTENT"` \| `"HIDE_RECOMMENDATION"` \| `"FILTER"` ; `enabled`: `boolean` ; `logic`: [`KMCRecommendationLogic`](enums/KMCRecommendationLogic.md) ; `maxProducts`: `number` ; `pageType`: `KMCRecommendationPagetype` ; `productThreshold`: `number` ; `recsKey`: `string` ; `segmentKey`: `null` \| `string` ; `segmentName`: `null` \| `string` ; `spotKey`: `string` ; `spotName`: `string` ; `title`: `string`  }, `"logic"` \| `"recsKey"` \| `"title"`> |
| `override?`  | `Partial`\<`KlevuRecommendationsEventV2Data`>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/sendRecommendationViewEvent/sendRecommendationViewEvent.ts:25](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/sendRecommendationViewEvent/sendRecommendationViewEvent.ts#L25)

[title] search
[path] Modules/

▸ **search**(`term`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Create a basic search to Klevu backend. Default ID for this query is `search`

### Parameters

| Name           | Type                                                             | Description                                        |
| -------------- | ---------------------------------------------------------------- | -------------------------------------------------- |
| `term`         | `string`                                                         | Search term from input                             |
| `options?`     | `Partial`\<[`KlevuSearchOptions`](docId\:oPnz3pXXIAZwE9oJVUONX)> | [KlevuSearchOptions](docId\:oPnz3pXXIAZwE9oJVUONX) |
| `...modifiers` | `KlevuFetchModifer`\[]                                           | -                                                  |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/search/search.ts:38](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/search/search.ts#L38)

[title] top
[path] Modules/

▸ **top**(`ids`): `KlevuFetchModifer`

Add given ids as first items in results

### Parameters

| Name  | Type        |
| ----- | ----------- |
| `ids` | `string`\[] |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/top/top.ts:10](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/top/top.ts#L10)

[title] moiresponsegenericoptions
[path] Modules/

Ƭ **MoiResponseGenericOptions**: `Object`

### Type declaration

| Name                     | Type                                                                                                 |
| ------------------------ | ---------------------------------------------------------------------------------------------------- |
| `genericOptions?`        | \{ `options`: \{ `chat`: `string` ; `name`: `string` ; `type`: `"message"` \| `"clearChat"`  }\[]  } |
| `genericOptions.options` | \{ `chat`: `string` ; `name`: `string` ; `type`: `"message"` \| `"clearChat"`  }\[]                  |

### Defined in

[connection/moi/moi.ts:76](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L76)

[title] recommendationvieweventmetadata
[path] Modules/

Ƭ **RecommendationViewEventMetaData**: [`KlevuKMCRecommendations`](docId\:Vo7OtiF0AXpgHUYvWUVrl)\[`"metadata"`]

### Defined in

[events/KlevuEvents.ts:27](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/events/KlevuEvents.ts#L27)

## Variables

### KlevuLastClickedProducts

• `Const` **KlevuLastClickedProducts**: `LastClickedProducts`

### Defined in

[store/lastClickedProducts.ts:153](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/store/lastClickedProducts.ts#L153)

[title] moimessages
[path] Modules/

Ƭ **MoiMessages**: ([`MoiResponseText`](docId:9S37kRMdItq5Dsi4dr6zO) | [`MoiResponseFilter`](docId:2_K2WkBpkWSaXYxOymHai) | [`MoiProducts`](docId\:oVFUBTviQeo-zUbPC4M5W) | [`MoiLocalMessage`](docId\:vMySWnBYqm_OowcAe4QGJ))\[]

### Defined in

[connection/moi/moi.ts:156](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L156)

[title] moimenuoptions
[path] Modules/

Ƭ **MoiMenuOptions**: `Object`

### Type declaration

| Name                  | Type                                                                                                                                                                                           |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `menuOptions?`        | \{ `options`: \{ `chat`: `string` ; `name`: `string` ; `options`: \{ `key`: `string` ; `validations`: `string` ; `value`: `string`  }\[] ; `type`: `"message"` \| `"customerSupport"`  }\[]  } |
| `menuOptions.options` | \{ `chat`: `string` ; `name`: `string` ; `options`: \{ `key`: `string` ; `validations`: `string` ; `value`: `string`  }\[] ; `type`: `"message"` \| `"customerSupport"`  }\[]                  |

### Defined in

[connection/moi/moi.ts:86](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L86)

[title] sendsearchevent
[path] Modules/

▸ **sendSearchEvent**(`override?`): `KlevuFetchModifer`

This modifier should be used in the case when user hits enter (or presses button) to see
all results from search.

### Parameters

| Name        | Type                        |
| ----------- | --------------------------- |
| `override?` | `Partial`\<`V1SearchEvent`> |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/sendSearchEvent/sendSearchEvent.ts:12](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/sendSearchEvent/sendSearchEvent.ts#L12)

[title] moiresponsefilter
[path] Modules/

Ƭ **MoiResponseFilter**: `Object`

### Type declaration

| Name                              | Type                                                                                                                                                                                                                                                                                 |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `filter`                          | \{ `note`: `string` \| `null` ; `options`: \{ `count`: `string` ; `name`: `string` ; `selected`: `boolean` \| `null` ; `value`: `string`  }\[] ; `settings`: \{ `chatFormat`: `string` ; `chatFormatEmpty`: `string` ; `key`: `string` \| `null` ; `label`: `string` \| `null`  }  } |
| `filter.note`                     | `string` \| `null`                                                                                                                                                                                                                                                                   |
| `filter.options`                  | \{ `count`: `string` ; `name`: `string` ; `selected`: `boolean` \| `null` ; `value`: `string`  }\[]                                                                                                                                                                                  |
| `filter.settings`                 | \{ `chatFormat`: `string` ; `chatFormatEmpty`: `string` ; `key`: `string` \| `null` ; `label`: `string` \| `null`  }                                                                                                                                                                 |
| `filter.settings.chatFormat`      | `string`                                                                                                                                                                                                                                                                             |
| `filter.settings.chatFormatEmpty` | `string`                                                                                                                                                                                                                                                                             |
| `filter.settings.key`             | `string` \| `null`                                                                                                                                                                                                                                                                   |
| `filter.settings.label`           | `string` \| `null`                                                                                                                                                                                                                                                                   |

### Defined in

[connection/moi/moi.ts:58](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L58)

[title] products
[path] Modules/

▸ **products**(`productIds`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Fetches list of products. All fields are fetched.

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `productIds`   | `string`\[]            |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/products/products.ts:16](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/products/products.ts#L16)

[title] moiresponsecontext
[path] Modules/

Ƭ **MoiResponseContext**: `Object`

### Type declaration

| Name      | Type                                         |
| --------- | -------------------------------------------- |
| `context` | [`MoiContext`](docId\:kIYizzef1kgLJcSqoO9pI) |

### Defined in

[connection/moi/moi.ts:44](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L44)

[title] searchcategory
[path] Modules/

▸ **searchCategory**(`term`, `options?`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Search helper function that sets correct settings

### Parameters

| Name       | Type                                                             | Description      |
| ---------- | ---------------------------------------------------------------- | ---------------- |
| `term`     | `string`                                                         | category to find |
| `options?` | `Partial`\<[`KlevuSearchOptions`](docId\:oPnz3pXXIAZwE9oJVUONX)> |                  |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/searchCategory/searchCategory.ts:13](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/searchCategory/searchCategory.ts#L13)

[title] moiresponsetext
[path] Modules/

Ƭ **MoiResponseText**: `Object`

### Type declaration

| Name                       | Type                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `message`                  | \{ `collectFeedback?`: `boolean` ; `id`: `string` ; `note`: `string` \| `null` ; `type`: `"text"` ; `value`: `string`  } |
| `message.collectFeedback?` | `boolean`                                                                                                                |
| `message.id`               | `string`                                                                                                                 |
| `message.note`             | `string` \| `null`                                                                                                       |
| `message.type`             | `"text"`                                                                                                                 |
| `message.value`            | `string`                                                                                                                 |

### Defined in

[connection/moi/moi.ts:48](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L48)

[title] moiproducts
[path] Modules/

Ƭ **MoiProducts**: `Object`

### Type declaration

| Name                            | Type                                                                                                                                                                                              |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `productData`                   | \{ `note`: `string` \| `null` ; `products`: [`MoiProduct`](docId\:tIPkvF85xDft2BF930T5A)\[] ; `totalResultsFound`: `string` ; `typeOfQuery`: [`KlevuTypeOfSearch`](enums/KlevuTypeOfSearch.md)  } |
| `productData.note`              | `string` \| `null`                                                                                                                                                                                |
| `productData.products`          | [`MoiProduct`](docId\:tIPkvF85xDft2BF930T5A)\[]                                                                                                                                                   |
| `productData.totalResultsFound` | `string`                                                                                                                                                                                          |
| `productData.typeOfQuery`       | [`KlevuTypeOfSearch`](enums/KlevuTypeOfSearch.md)                                                                                                                                                 |

### Defined in

[connection/moi/moi.ts:101](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L101)

[title] moiproduct
[path] Modules/

Ƭ **MoiProduct**: `Object`

### Type declaration

| Name              | Type                                                              |
| ----------------- | ----------------------------------------------------------------- |
| `currency`        | `string`                                                          |
| `id`              | `string`                                                          |
| `image`           | `string`                                                          |
| `itemGroupId`     | `string`                                                          |
| `name`            | `string`                                                          |
| `noOfVariants`    | `number`                                                          |
| `options`         | \{ `chat`: `string` ; `intent`: `string` ; `name`: `string`  }\[] |
| `originalContent` | `null` \| `string`                                                |
| `price`           | `string`                                                          |
| `salePrice`       | `string`                                                          |
| `shortDesc`       | `string`                                                          |
| `url`             | `string`                                                          |

### Defined in

[connection/moi/moi.ts:110](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L110)

[title] similarproducts
[path] Modules/

▸ **similarProducts**(`ids`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Fetch similiar products based on list of ids

### Parameters

| Name           | Type                   | Description                           |
| -------------- | ---------------------- | ------------------------------------- |
| `ids`          | `string`\[]            | similiar to these ids or itemgroupids |
| `options?`     | `Partial`\<`Options`>  |                                       |
| `...modifiers` | `KlevuFetchModifer`\[] | -                                     |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/similarProducts/similarProducts.ts:26](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/similarProducts/similarProducts.ts#L26)

[title] moiresponseobjects
[path] Modules/

Ƭ **MoiResponseObjects**: [`MoiResponseText`](docId:9S37kRMdItq5Dsi4dr6zO) | [`MoiResponseFilter`](docId:2_K2WkBpkWSaXYxOymHai) | [`MoiResponseGenericOptions`](docId\:DMCLo2pR2oMPSRjoC44sL) | [`MoiMenuOptions`](docId\:JAsD1cuAj7d5dLUuISAOR) | [`MoiProducts`](docId\:oVFUBTviQeo-zUbPC4M5W) | [`MoiActionsMessage`](docId\:WrJO6fGuUG_px6-6W4o1Z)

### Defined in

[connection/moi/moi.ts:148](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L148)

[title] moiresponse
[path] Modules/

Ƭ **MoiResponse**: `Object`

### Type declaration

| Name   | Type                                                                              |
| ------ | --------------------------------------------------------------------------------- |
| `data` | \[[`MoiResponseContext`](docId\:y9i3RA_lBeg3ik0jpe68u), ...MoiResponseObjects\[]] |

### Defined in

[connection/moi/moi.ts:40](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L40)

[title] overridesettings
[path] Modules/

▸ **overrideSettings**(`settingsToOverride`): `KlevuFetchModifer`

Tool to override any query settings. Be careful with this, as it can override any query settings and can cause unexpected results.

### Parameters

| Name                 | Type                                                                 |
| -------------------- | -------------------------------------------------------------------- |
| `settingsToOverride` | `Partial`\<[`KlevuBaseQuerySettings`](docId\:DyD-sdD9prRQ0gcOerUbZ)> |

### Returns

`KlevuFetchModifer`

### Defined in

[modifiers/overrideSettings/overrideSettings.ts:11](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/modifiers/overrideSettings/overrideSettings.ts#L11)

[title] visuallysimilar
[path] Modules/

▸ **visuallySimilar**(`itemGroupIds`, `options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Visually similar recommendation query

### Parameters

| Name           | Type                   |
| -------------- | ---------------------- |
| `itemGroupIds` | `string`\[]            |
| `options?`     | `Partial`\<`Options`>  |
| `...modifiers` | `KlevuFetchModifer`\[] |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

### Defined in

[queries/visuallySimilar/visuallySimilar.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/visuallySimilar/visuallySimilar.ts#L24)

[title] moisavedfeedback
[path] Modules/

Ƭ **MoiSavedFeedback**: `Object`

### Type declaration

| Name      | Type               |
| --------- | ------------------ |
| `id`      | `string`           |
| `reason?` | `string`           |
| `thumbs`  | `"up"` \| `"down"` |

### Defined in

[connection/moi/moi.ts:162](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L162)

[title] trendingproducts
[path] Modules/

▸ **trendingProducts**(`options?`, `...modifiers`): [`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

Create a trending products search query. Id for this query is `trendingProducts`



Simple example

```text
const result = await KlevuFetch(
 trendingProducts()
)

console.log(result.getQueries("trendingProducts").records)
```

### Parameters

| Name           | Type                                                             | Description                            |
| -------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `options?`     | `Partial`\<[`KlevuSearchOptions`](docId\:oPnz3pXXIAZwE9oJVUONX)> | [search](docId\:AtPkL6cEuhS9C8oYWZV6i) |
| `...modifiers` | `KlevuFetchModifer`\[]                                           | -                                      |

### Returns

[`KlevuFetchFunctionReturnValue`](docId\:T803lqj3C91t_7d1wZito)

See KlevuFetchFunction

### Defined in

[queries/trendingProducts/trendingProducts.ts:24](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/queries/trendingProducts/trendingProducts.ts#L24)

[title] startmoi
[path] Modules/

▸ **startMoi**(`options?`): `Promise`\<[`MoiSession`](classes/MoiSession.md)>

### Parameters

| Name      | Type                                              |
| --------- | ------------------------------------------------- |
| `options` | [`MoiStartOptions`](docId\:lkD7d8i4M6XW1DxztVOQR) |

### Returns

`Promise`\<[`MoiSession`](classes/MoiSession.md)>

### Defined in

[connection/moi/moi.ts:235](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L235)

[title] moistartoptions
[path] Modules/

Ƭ **MoiStartOptions**: `Object`

### Type declaration

| Name                                | Type                                                                                                                          | Description                                                                                |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `mode?`                             | [`MoiChatModes`](docId\:emBLFzL6rES1tkprIbcb6)                                                                                | The mode to use. If undefined will use the default Moi mode                                |
| `onAction?`                         | (`action`: [`MoiActionsMessage`](docId\:WrJO6fGuUG_px6-6W4o1Z)\[`"actions"`]\[`"actions"`]\[`number`]) => `boolean` \| `void` | Action listener for actions                                                                |
| `onMessage?`                        | () => `void`                                                                                                                  | Called when a message is received from Moi                                                 |
| `onRedirect?`                       | (`url`: `string`) => `void`                                                                                                   | Custom redirect handler                                                                    |
| `pqaWidgetId?`                      | `string`                                                                                                                      | PQA widgetId for the PQA application                                                       |
| `productId?`                        | `string`                                                                                                                      | productId for the PQA application                                                          |
| `settings?`                         | \{ `alwaysStartConversation?`: `boolean` ; `configOverride?`: [`KlevuConfig`](classes/KlevuConfig.md)  }                      | -                                                                                          |
| `settings.alwaysStartConversation?` | `boolean`                                                                                                                     | Always sends the initial message to Moi even if there are no messages stored for that case |
| `settings.configOverride?`          | [`KlevuConfig`](classes/KlevuConfig.md)                                                                                       | Override the config                                                                        |
| `url?`                              | `string`                                                                                                                      | URL for the PQA application                                                                |

### Defined in

[connection/moi/moi.ts:183](https://github.com/klevultd/frontend-sdk/blob/492d3760/packages/klevu-core/src/connection/moi/moi.ts#L183)

[space] Klevu PHP SDK (/php-sdk)

[title] Analytics
[path] Examples / How To/


[title] Account Management
[path] Examples / How To/


[title] Quickstart
[path] /

# Installation

First, install the `klevu/php-sdk` library in your application. We recommend using composer to ensure dependencies are managed appropriately, and to hook into autoloading automatically.
You can also install directly from [source \[Github\]](https://github.com/klevu/php-sdk), and handle autoloading yourself.

```shell
composer require klevu/php-sdk
```

# Retrieve Your Access Tokens

Next, you will need to locate your JS API Key and REST AUTH Key for the account you are integrating. These can be found under Store Settings > Store Info > Shop Info > Integration when logged into [Klevu Merchant Center](https://box.klevu.com).

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/2N6gc-Ww_NhBwcfExYb4n_image.png)

:::hint{type="info"}
Note: in our examples we will hardcode these credentials. When building your application, you should save and retrieve them from our existing configuration storage.
:::

# Create an Account Credentials Object

Whenever you need to interact with Klevu via one of the public services, you will need to provide the credentials above in a standard format - in this case, the `AccountCredentials` object.

Create a new PHP script

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Model\AccountCredentials;

$accountCredentials = new AccountCredentials(
    jsApiKey: '[Your JS API Key]', // eg klevu-1234567890
    restAuthKey: '[Your REST AUTH KEY]', // eg ABCDE1234567890
);

```

## Instatiate a Service Class&#x20;

Finally, choose which service you need to interact with; instatiate its service class; and execute your request.&#x20;

There are simple code examples for all main services in the How-To, some popular ones are listed below

- Account Management : [Retrieve Klevu Account Details](docId:1t7gUNUfpS0b-ICOkGwAr)
- Analytics : [Send Analytics Events Data](docId\:rdq1zpjutlXhP4yH9xsWm)
- Indexing : [Send Records for Indexing](docId\:wacVz7cvZ6qQV8kkNSyRB)


[title] Managing Attributes
[path] Guide/Features/Data Indexing/

When sending data for indexing, there are a number of default attributes which can be sent and used for searching and/or as facets. Your store, however, likely has custom or non-standard attributes which you would like to use in your search solutions. Unlike the old [XML-based indexing](https://docs.klevu.com/indexing-apis/XML), the [JSON API](https://docs.klevu.com/indexing-apis/JSON) requires attributes to be registered before they can be included in an indexing payload otherwise the batch request will be rejected.

The PHP-SDK provides service classes to retrieve attributes present in your indexes, as well as to add; update; or delete attribute definitions.

## Attribute Definitions

Attributes are defined by the [Attribute](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/Attribute.php) model and contain the following information.

| Property        | Description                                                                                                                                                                                                                                                                                                                                        |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `attributeName` | `string`<br />Unique identifier for the attribute. Must be alphnumeric and can include underscores (`_`), but cannot start or end with an underscore.<br />Example: `"my_custom_attribute"`<br />*Note: value is defined during object instantiation and cannot be changed post hoc*                                                               |
| `datatype`      | `string`<br />Type of data which is expected to be sent in payloads. See table below for options.<br />Example: `"STRING"`<br />*Note: value is defined during object instantiation and cannot be changed post hoc*                                                                                                                                |
| `label`         | `array<string, string>`<br />Array of label(s) used when rendering attribute, for example in facets.<br />Value should always contain one key named `default`, along with optional values for different locales.<br />Example:<br />`[`<br />`    'default' => 'My Custom Attribute',`<br />`    'es-ES' => 'Mi atributo personalizado',`<br />`]` |
| `searchable`    | `boolean`<br />Whether this attribute's data should be considered when searching                                                                                                                                                                                                                                                                   |
| `filterable`    | `boolean`<br />Whether this attribute should be used in faceting on the storefront                                                                                                                                                                                                                                                                 |
| `returnable`    | `boolean`<br />Whether this attributer's value should be returned in search payloads, allowing use in storefront template                                                                                                                                                                                                                          |
| `immutable`     | `boolean`<br />Whether this attribute's properties can be updated.                                                                                                                                                                                                                                                                                 |

:::hint{type="warning"}
Attribute definitions apply to all record types, meaning you cannot define an attribute with the same name and different definitions for KLEVU\_PRODUCT and KLEVU\_CATEGORY records, for example.

If you need multiple definitions for the same attribute name across different record types, you should define unique names - we recommend using a prefix, such as `category__attr` / `product__attr` - and handling mapping within your application.
:::

:::hint{type="info"}
Note, data validity is not checked within the model itself but is performed by the [AttributeValidator](https://github.com/klevu/php-sdk/blob/master/src/Validator/Indexing/AttributeValidator.php) . This validator is not executed until you interact with Klevu APIs via the [AttributesService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/AttributesService.php) class, meaning invalid attribute names or datatypes, for example, will not be picked up at time of definition.
:::

### Data Types

The data type of an attribute is used by the indexing APIs to determine whether provided data in an indexing payload is valid. For example, defining an attribute as STRING and sending an array of integers would be rejected and cause the Indexing\BatchService to return a BadRequestException.

:::hint{type="warning"}
Despite the DataType enum, the Attribute model's `datatype` property is a string. This is to ensure that as new data types are introduced to the API, instantiation of Attribute models does not fail.

Be aware that attempting to update attributes with datatypes not available in the DataType enum will fail validation.
:::

Data Types currently supported the the PHP-SDK:

| Datatype   | Description                                                                                                                                                                                                                                          |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| STRING     | Default attribute type expecting any content, providing it is transmitted as a `string` type                                                                                                                                                         |
| NUMBER     | Attribute value must be sent as an `integer` or `float`<br />*Note: not currently supported for creating custom attributes*                                                                                                                          |
| DATETIME   | Attribute value must be sent as a string in [ISO-8601 format](https://www.iso.org/iso-8601-date-and-time-format.html).<br />Special handling may be performed in Klevu's indexes<br />*Note: not currently supported for creating custom attributes* |
| MULTIVALUE | Attribute value must be sent as an array (with numeric keys, rather than a hash or object). Individual values may be any scalar type.                                                                                                                |
| JSON       | Attribute value must be sent as a valid JSON string.<br />*Note: not currently supported for creating custom attributes; some core attributes will use this type*                                                                                    |
| BOOLEAN    | Attribute value must be sent as a `boolean`<br />*Note: not currently supported for creating custom attributes; some core attributes will use this type*                                                                                             |

**Protected Data Types**

As noted in the table above, some data types are not available to custom attributes. The DATETIME and NUMBER types will be available in future versions, but are not currently used by any attribute; JSON and BOOLEAN are used by some core (immutable) attributes, but are not available to create custom attributes with.

### Immutable Attributes

Immutable attributes cover those defined by default in Klevu's indexes and include, for example, `name` ; `sku`; and `url` . Attributes retrieved via the AttributesService `get` or `getByName` methods will havethis value populated from the API response.

Attributes with the `immutable` flag set to true cannot have their data changed using setters. For example, the following code would throw a `CouldNotUpdateException`

```php
<?php

$attribute = new Attrbute('attr', 'STRING');
$attribute->setSearchable(true); // OK

$attribute->setImmutable(true);
$attribute->setSearchable(false); // Throws exception
```

Immutable attributes cannot be sent for add, update, or delete operations via the AttributeService and will be rejected during the validation stage.

Note that the immutable flag can be disabled at any time to circumvent these restrictions, however disabling locks and sending update / delete requests for attributes defined as immutable in Klevu's indexes will result in a BadRequestException as the APIs will reject the request.
Additionally, the immutable flag is ignored when creating or updating an attribute via the API.

## Listing Existing Attributes

The `AttributesService::get` method will query the `indexing.ksearchnet.com/v2/attributes` endpoint using your JS API Key and REST AUTH Key (available via Store Settings in KMC) and return an AttributeIterator containing Attribute models representing all existing attributes in your installation.

Additionally, you can use `AttributesService::getByName` to query a single attribute, returning either an Attribute model or null.

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Data used to generate the request bearer token is logged at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level

*More information and code samples can be found under&#x20;*[Examples / How To > Data Indexing > List Existing Attributes](docId\:DveGgsYQbmqnUX0IZ2dT9)

## Creating or Updating Attributes

The `AttributesService::put` method will send a PUT request to the `indexing.ksearchnet.com/v2/attributes/[ATTRIBUTE_NAME]` endpoint using your JS API Key and REST AUTH Key (availble via Store Settings in KMC).

Data is provided as an `Attribute` object and validated using the `AttributeValidator` .

:::hint{type="warning"}
When updating an attribute, the attribute name is both case-insensitive and immutable, meaning if you have an existing attribute called `my_attribute` and you submit a request to update `MY_ATTRIBUTE`, the changes will be applied but the attribute will retain the name `my_attribute`
:::

### Handling Changes to Data Type

An attribute's datatype cannot be changed after registration. As such, if you need to change an attribute (for example, from a string to a multivalue), you must first delete the existing attribute and recreate it with the new definition.

**Important**: this will delete all existing data for this attribute from the Klevu indexes and require a full resync of your catalog data.

*More information and code samples can be found under&#x20;*[Examples / How To > Data Indexing > Add, Update, or Delete Indexing Attributes](docId\:dc1izCGc4VSnlYPS_ejYA)

### Syncing Data for New Attributes

Data for custom attributes should be sent within the `attributes` section of an indexing request, and should be formatted as an object containing at least the "default" key with the attribute's value. Alternative language values can be sent within this array, identified by a language code key. For more information, see the guide on Synchronising Data

:::hint{type="info"}
Note, there may be a short delay between creating an attribute and it being available for us when synchronising data. We recommend waiting for 60 seonds after registering an attribute before sending an indexing request referencing it.
:::

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure.
- Prior to transmitting data, the Attribute data is validated, throwing a `ValidationException` on failure.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Data used to generate the request bearer token is logged at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level

## Deleting Attributes

The `AttributesService` will send a DELETE request to the `indexing.kseachnet.com/attributes/[ATTRIBUTE_NAME]` endpoint using your JS API Key and REST AUTH Key (availble via Store Settings in KMC).

Data is provided either as a string (`deleteByName`) or by providing an Attribute object to `delete`, from which the name is extracted and passed to `deleteByName.`

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure.
- Prior to transmitting data, the Attribute name is validated, throwing a `ValidationException` on failure.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Data used to generate the request bearer token is logged at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level

*More information and code samples can be found under&#x20;*[Examples / How To > Data Indexing > Add, Update, or Delete Indexing Attributes](docId\:dc1izCGc4VSnlYPS_ejYA)

[title] Change Endpoints Used In API Calls
[path] Examples / How To/

## Loading Endpoints from Account Data

Services which interact with Klevu's APIs use a common class to provide endpoint URLs for requests. In the majority of cases, the domains provided will the ones needed to send or receive data. The primary exception is when sending search requests (including for [Smart Category Merchandising](https://www.klevu.com/solutions/category-merchandising/)) where the search URL varies by account.
Note: *at time of writing, no SDK servies interact with search URLs*

The BaseUrlsProvider class allows updating base URLs from an Account object (see **Examples** > **How To** > **Account Management** > **Retrieve Klevu Account Details**) either via the constructor or after instantiation.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Model\Account;
use Klevu\PhpSDK\Model\AccountFactory;
use Klevu\PhpSDK\Provider\BaseUrlsProvider;

$accountFactory = new AccountFactory();
$account = $accountFactory->create(
    data: [
        Account::FIELD_SEARCH_URL => 'eucs27v2.ksearchnet.com',
    ],
);

$baseUrlsProvider = new BaseUrlsProvider(
    account: $account,
);
$searchUrl = $baseUrlsProvider->getSearchUrl(); // eucs27v2.ksearchnet.com

$account->setSearchUrl('eucs30v2.ksearchnet.com');
$baseUrlsProvider->updateFromAccount(
    account: $account,
);
$searchUrl = $baseUrlsProvider->getSearchUrl(); // eucs30v2.ksearchnet.com

```

An example use case would be to load and cache Klevu account information locally, which can be used to create Account objects (via the AccountFactory) for subsequent requests, rather than sending API requests on each page load.

## Injecting Endpoints Into Services

The BaseUrlsProvider instance can then be used by any service that interacts with Klevu, all of which accept a BaseLoggerInterface instance via their constructor.

Note: *if you are integrating into a modern framework, you should implement this via your dependency injection system.*

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Model\Account;
use Klevu\PhpSDK\Model\AccountFactory;
use Klevu\PhpSDK\Provider\BaseUrlsProvider;
use Klevu\PhpSDK\Service\Account\AccountFeaturesService;
use Klevu\PhpSDK\Service\Account\AccountLookupService;
use Klevu\PhpSDK\Service\Account\UpdateStoreFeedUrlService;
use Klevu\PhpSDK\Service\Analytics\CollectService as AnalyticsCollectService;
use Klevu\PhpSDK\Service\Indexing\AttributesService;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;
use Klevu\PhpSDK\Service\Indexing\BatchService;

$accountFactory = new AccountFactory();
$account = $accountFactory->create(
    data: [
        Account::FIELD_SEARCH_URL => 'eucs27v2.ksearchnet.com',
    ],
);

$baseUrlsProvider = new BaseUrlsProvider(
    account: $account,
);

// Account
$accountFeatureService = new AccountFeaturesService(
    baseUrlsProvider: $baseUrlsProvider,
);
$accountLookupService = new AccountLookupService(
    baseUrlsProvider: $baseUrlsProvider,
);
$updateStoreFeedUrlService = new UpdateStoreFeedUrlService(
    baseUrlsProvider: $baseUrlsProvider,
);

// Analytics
$collectService = new AnalyticsCollectService(
    baseUrlsProvider: $baseUrlsProvider,
);

// Indexing
$attributesService = new AttributesService(
    baseUrlsProvider: $baseUrlsProvider,
);
$batchService = new BatchService(
    baseUrlsProvider: $baseUrlsProvider,
);
$batchDeleteService = new BatchDeleteService(
    baseUrlsProvider: $baseUrlsProvider,
);
```

***

## Source Code Reference

- Model\\[Account](https://github.com/klevu/php-sdk/blob/master/src/Model/Account.php)
- Model\\[AccountFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountFactory.php)
- Provider\\[BaseUrlsProvider](https://github.com/klevu/php-sdk/blob/master/src/Provider/BaseUrlsProvider.php)
- Provider\\[BaseUrlsProviderInterface](https://github.com/klevu/php-sdk/blob/master/src/Provider/BaseUrlsProviderInterface.php)


[title] Guide
[path] /


[title] Interfaces and Service Contracts
[path] Guide/Technical / Architecture/

## Interface Usage

Interfaces are used for many models, services and validators where it may be beneficial to application integrating the SDK to replace functionality entirely, or implement alternative / additional versions (such as with validators or providers).

Replacing a concrete implementation of an interface should be avoided if possible; if necessary, the native class should be extended rather than replaced entirely. Dependency injection should be used to replace the smallest possible component to enable customisations, especially in composite classes such as the UserAgentProvider.

## Service Contracts

Interface will often be found as close to the aplicable implementations as possible, many times in the same folder. An exception to this is the root `Api` directory, which defines contracts for the primary models and services used in the php-sdk package.

Interfaces within the `Api` directory - as well as classes tagged `@api` should be considered stable within the major version in which they appear. This means that the class will not be removed or have its method signatures changed without bumping the major version of the application (eg from 1.x to 2.x). This includes the addition of new methods or interfaces.

:::hint{type="info"}
Note, changes to non-api classes will still occur within minor and, occasionally, patch releases. This may include adding new classes / methods / optional arguments in public methods.
Any potentially breaking changes will always accompany a major version upgrade. This may include removing classes or methods, or adding new mandatory arguments to existing public methods.
:::




[title] Send Analytics Events Data
[path] Examples / How To/Analytics/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Sending Analytics Events Data

To send analytics event data to Klevu, you will need your Klevu API key (see Quickstart for details). Note that, unlike other services, the analytics endpoint belongs to the Klevu Storefront API and, as such, does not require a private key (REST AUTH Key).

Next, extract the order and customer information to be sent from your application, including all applicable line items. As each system differs in storage and retrieval of data, the examples below simply contain hardcoded data.

Instantiate a new `EventIterator` object and populate with `Event` items. Note, while you can create these using `new Event`, it is recommended to use the `EventFactory` class for ease of development and future compatibility.
Events can be added to the iterator's constructor, or after instantiation using `addItem()`

Finally, create an `Analytics\CollectService` object and call the `send` method with the Event collection, catching and handling any exception thrown during execution.

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.



```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\Analytics\Collect\EventFactory;
use Klevu\PhpSDK\Model\Analytics\Collect\EventIterator;
use Klevu\PhpSDK\Model\Analytics\Collect\EventType;
use Klevu\PhpSDK\Service\Analytics\CollectService;

$eventFactory = new EventFactory();

$events = new EventIterator(
    data: [
        $eventFactory->create(
            data: [
                'event' => EventType::ORDER_PURCHASE->value,
                'apikey' => 'klevu-1234567890',
                'version' => '1.0.0',
                'userProfile' => [
                    'ipAddress' => '127.0.0.1',
                    'email' => 'contact@klevu.com',
                ],
                'data' => [
                    'items' => [
                        [
                            'order_id' => 'KLEVU12345',
                            'order_line_id' => '12343',
                            'item_name' => 'Example Product',
                            'item_id' => 'PROD_42-VAR_001',
                            'item_group_id' => 'PROD_42',
                            'item_variant_id' => 'VAR_001',
                            'unit_price' => 3.14,
                            'currency' => 'EUR',
                            'units' => 42,
                        ],
                    ],
                ],
            ],
        ),
    ],
);
$events->addItem(
    item: $eventFactory->create(
        data: [
            'event' => 'order_purchase',
            'apikey' => 'klevu-12345',
            'version' => '1.0.0',
            'userProfile' => [
                'ipAddress' => '111.11.11.1',
                'email' => 'user@klevu.com',
            ],
            'data' => [
                'items' => [
                    [
                        'order_id' => '1223434',
                        'order_line_id' => 'ABC-12343',
                        'item_name' => '45RU,800x1070,N-Type,D,NoS,CM,WH,EA',
                        'item_id' => '75882',
                        'item_group_id' => '75882',
                        'item_variant_id' => '75882',
                        'unit_price' => 6033.42,
                        'currency' => 'USD',
                        'units' => 2,
                    ],
                    [
                        'order_id' => '1223435',
                        'order_line_id' => 'ABC-12344',
                        'item_name' => 'NoS,CM,WH,EA',
                        'item_id' => '75883',
                        'item_group_id' => '75883',
                        'item_variant_id' => '75883',
                        'unit_price' => 6033.42,
                        'currency' => 'USD',
                        'units' => 1,
                    ],
                ],
            ],
        ],
    ),
);

$analyticsCollectService = new CollectService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

$response = null;
try {
    $response = $analyticsCollectService->send($events);
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$sentSuccessfully = $response?->isSuccess() ?: false;
$messages = $response?->getMessages() ?: [];

```

***

## Source Code Reference

- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\Analytics\Collect\\[Event](https://github.com/klevu/php-sdk/blob/master/src/Model/Analytics/Collect/Event.php)
- Model\Analytics\Collect\\[EventFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/Analytics/Collect/EventFactory.php)
- Model\Analytics\Collect\\[EventIterator](https://github.com/klevu/php-sdk/blob/master/src/Model/Analytics/Collect/EventIterator.php)
- Model\Analytics\Collect\\[EventType](https://github.com/klevu/php-sdk/blob/master/src/Model/Analytics/Collect/EventType.php)
- Service\\[Analytics\CollectService](https://github.com/klevu/php-sdk/blob/master/src/Service/Analytics/CollectService.php)


[title] List Existing Attributes
[path] Examples / How To/Data Indexing/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Retrieve All Attributes for an Account

To retrieve attributes used by Klevu's XML Feed Monitoring service, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `Indexing\AttributeService` object and call the `get` method to return a collection of all attributes registered in Klevu indexing.
The `get` method will throw exceptions if any issues arise, so you should catch and handle these appropriately.

At this point, you will have an `AttributeIterator` object containing `Attribute` models for all registered attributes, which can be filtered and used in subsequent operations.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Indexing\AttributesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);
$attributesService = new AttributesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

try {
    $attributes = $attributesService->get(
        accountCredentials: $accountCredentials,
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}
```

### Filter Attributes

If you need to filter the return value of `get`, for example to remove immutable attributes or to identify attributes of a specific data type, you can call the `filter` method with your callback.&#x20;

Note: filtering an iterator in this way will return a copy, and will not modify the data contained within the original return object.

```php
<?php

// snip

$customAttributes = $attributes->filter(
    callback: static fn (AttributeInterface $attribute): bool => !$attribute->isImmutable(),
);
```

## Retrieve a Specific Attribute by Name

To retrieve a registered attribute by name, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `Indexing\AttributeService` object and call the `getByName` method with your credentials and the name of the attribute being search for.
The `getByName` method will throw exceptions if any issues arise, so you should catch and handle these appropriately.

At this point, you will have either an `Attribute` object or null.

:::hint{type="info"}
Note: this method does not map to a discrete API endpoint. Its purpose is essentially syntactic sugar, wrapping `get` and `filter` calls described above.
:::

:::hint{type="warning"}
The `attributeName` value is not case sensitive in Klevu's indexer and, therefore, is not case sensitive in name lookups in the PHP-SDK.
For example, a request for `example_attribute` may return `EXAMPLE_ATTRIBUTE` or other cased variations; though only one attribute (at most) will ever be returned from the API.

The `attributeName` property will reflect the case used at time of registration.
:::

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Indexing\AttributesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);
$attributesService = new AttributesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

try {
    $attribute = $attributesService->getByName(
        accountCredentials: $accountCredentials,
        attributeName: 'example_attribute',
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}
```

***

## Source Code Reference

- Api\Model\Indexing\\[AttributeInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/AttributeInterface.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Service\Indexing\\[AttributesService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/AttributesService.php)


[title] Examples / How To
[path] /


[title] Untitled
[path] /


[title] Synchronising Data
[path] Guide/Features/Data Indexing/

## Creating or Updating Records

Batches of records can be sent to the indexing endpoint (`indexing.ksearchnet.com/v2/batch`) in order to add or update search data using the Indexing\BatchService.

Data is sent as a collection of Record objects (within a RecordIterator), which are transmitted as a single request. Note that if too many records are included in the same batch, the request will be rejected (either by the PHP-SDK validation or the API itself).
The implementing application is responsible for creating and processing batches.

Data contained within a Record includes:

| Field        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`         | `string` Required<br />Unique ID for the record in your indexes<br />Examples: `"1"`, `"categoryid__12345"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `type`       | `string` Required<br />Type of record, such as product or category. Custom values are allowed.<br />Examples: `"KLEVU_PRODUCT"`, `"KLEVU_CATEGORY"`, `"KLEVU_CMS"`, `"ACME_RECORD"`<br />*Note: the type of record will determine the degree of data validation performed by the API with, for example, KLEVU\_PRODUCT records requiring attribute fields not present in other record types*                                                                                                                                                                                                                                                                                                                                       |
| `relations`  | `array`<br />Array of relation defintions, such as categories and parent products.<br />Example:<br />`[`<br />`    'categories' => [`<br />`        'values' => [`<br />`            'CATEGORY001',`<br />`            'CATEGORY002',`<br />`        ],`<br />`    ],`<br />`    'parentProduct' => [`<br />`        'values' => [`<br />`            'PARENT_PRODUCT_001',`<br />`        ],`<br />`    ],`<br />`]`<br /><br />*Note: no validation is performed on content of this field; refer to the API definition for details of structure and content*                                                                                                                                                                    |
| `attributes` | `array`<br />Array of record data, comprising core and custom attributes (if present)<br />Example:<br />`[`<br />`    'name' => [`<br />`        'default' => 'Men Regular Mid Rise Dark Blue Jeans',`<br />`        'fi-FI' => 'Miesten tavalliset Mid Rise tummansiniset farkut',`<br />`    ],`<br />`    'sku' => 'SKU0001',`<br />`    'image' => [`<br />`        'default' => [`<br />`            'url' => 'https://www.klevu.com/image.jpg',`<br />`            'type' => 'default',`<br />`            'height' => 100,`<br />`            'width' => 100,`<br />`        ],`<br />`     ],  `<br />`]`<br />*Note: validation is performed for attribute name validity, but missing or invalid fields are not checked* |
| `display`    | `array`<br />Array of data which should be returned in search queries for use in storefront templates<br />Example:<br />`[`<br />`    'default' => [`<br />`        'additionalProp1' => [],`<br />`    ],`<br />`    'additionalProp1' => [],`<br />`]`<br />*Note: validation is performed for attribute name validity*                                                                                                                                                                                                                                                                                                                                                                                                         |

:::hint{type="warning"}
IDs must be unique within your entire index, not just within a specific record type. For example, you could not send records with ID "1" for both "KLEVU\_PRODUCT" and "KLEVU\_CATEGORY".

If you are synchronising multiple record types which share IDs in your application, we recomend using a prefix for most or all records to ensure their uniqueness. For example `product__1` / `category__1`
:::

:::hint{type="info"}
Note, data validity is not checked within the model itself, but is performed by the RecordValidator. This validator is not executed until you interact with Klevu APIs via the Indexing\BatchService, meaning invalid ids or attribute names, for example, will not be picked up at time of definition.
:::

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure.
- Prior to transmitting data, the Record data is validated, throwing a `ValidationException` on failure.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Data used to generate the request bearer token is logged at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` levelDeleting Records&#x20;

*More information and code samples can be found under&#x20;*[Examples / How To > Data Indexing > Send Records for Indexing](docId\:wacVz7cvZ6qQV8kkNSyRB)

## Deleting Records

Batches of record IDs can be sent to the indexing endpoint (`indexing.ksearchnet.com/v2/batch/delete`) in order to remove search data using the Indexing\Batch\DeleteService.

Data is provided as an array of strings corresponding to the ID value used when creating the record (above); type is not required as ID is unique across all records.

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure.
- Prior to transmitting data, the Record IDs are validated, throwing a `ValidationException` on failure.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Data used to generate the request bearer token is logged at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` levelDeleting Records&#x20;

*More information and code samples can be found under&#x20;*[Examples / How To > Data Indexing > Delete Records from Inde](docId\:aQcZmHzhC20d6Ko4n9nxJ)

[title] Technical / Architecture
[path] Guide/


[title] Analytics
[path] Guide/Features/

Events can be sent to the analytics endpoint ([https://stats.ksearchnet.com/analytics/collect](https://stats.ksearchnet.com/analytics/collect)) in order to record analytics data for use in conversion tracking using the Analytics\CollectService.

Data is sent as a collection of Event objects (within an EventIterator).&#x20;
While multiple Events can be sent in a single request, each individual event must be associated with a single event action (such as order purchase), Klevu account, and user profile (eg, customer details).

:::hint{type="info"}
Note: only purchase events are currently available to send via the php-sdk
:::

Data contained within an event includes

| Field          | Description                                                                                                                                                                                                                                                                                                                                                                         |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `event`        | The type of event / action to be tracked<br />Example: `"order_purchase"`                                                                                                                                                                                                                                                                                                           |
| `apikey`       | The JS API (public) key for the Klevu account receiving the data<br />Example: `"klevu-1234567890`                                                                                                                                                                                                                                                                                  |
| `version`      | Which version of the Event format the transmitted data adheres to. Where backwards-compatibility breaking changes (such as new mandatory fields) are introduced to this object, an incremented version will be available.<br />Example: `1.0.0`                                                                                                                                     |
| `user_profile` | Object containing identifying information about the visitor performing the tracked action. Includes<br />* `ipAddress`
* `email`<br />*Note: this informational is optional, but without it conversion information may not be attributed correctly.*<br />*Please ensure GDPR and other privacy concerns are accounted for before transmitting personally identifiable information* |
| `data`         | JSON object containing event data for recording. Content of this data will vary based on the `event` and/or `version` values of the object. <br />Example: *see below*                                                                                                                                                                                                              |

### Event Data for Order Purchase

The data for events of type `order_purchase` is an object with a single `items` key. The `data.items` property comprises an array of objects for each line item, with the following information.

| Field             | Description                                                                                                                                                                                                                                              |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `order_id`        | String identifying the order to which this item belongs within the source system<br />Example: `"KLEVU12345"`                                                                                                                                            |
| `order_line_id`   | String identifying the order line item within the source system<br />Example: `"12345"`                                                                                                                                                                  |
| `item_name`       | The name of the product purchased                                                                                                                                                                                                                        |
| `item_id`         | Where a variant of a complex product has been purchased, this should be a combination of the group and variant ids; for simple products, use the product id<br />Examples: `"SKU_12345"`; `"PROD_42-VAR_001"`                                            |
| `item_group_id`   | String identifying the parent product within the source system, where the purchased item is a variant of a complex product.<br />Leave empty or use the variant id where purchased product is not configurable<br />Examples: `"SKU_12345"`; `"PROD_42"` |
| `item_variant_id` | String identifying the purchased product variant within the source system<br />Example: `"SKU_12345"`; `"VAR_001"`                                                                                                                                       |
| `unit_price`      | Decimal representation of the purchased price for the order line (ie, item price × quantity) without a currency code<br />Example: `3.14`                                                                                                                |
| `currency`        | Three character code for the currency in which the order was placed<br />Example: `"EUR"`                                                                                                                                                                |
| `units`           | Integer representation of the quantity purchased for this order line<br />Example: `42`                                                                                                                                                                  |

*For more information, please see the&#x20;*[Storefront APIs documentation](https://docs.klevu.com/apis/smart-search-analytics-events)**

:::hint{type="warning"}
Sending data to older productTracking endpoints (eg [https://stats.ksearchnet.com/analytics/productTracking](https://stats.ksearchnet.com/analytics/productTracking)) is not supported in the php-sdk
:::

### Validation and Exception Handling

- Prior to transmitting data, each individual event is validated; any invalid records will throw a `ValidationException` , preventing transmission of *all* events
  - Validation is performed on both the event properties, and the event data. Event data validation will differ depending on the event type and version.
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level

*More information and code samples can be found under&#x20;*[Examples / How To > Analytics > Send Analytics Events Data](docId\:rdq1zpjutlXhP4yH9xsWm)


[title] Logging
[path] Examples / How To/

The PHP-SDK does not specify a dependency on any logging packages, meaning no logging will be performed out of the box. This is an intentional design decision to ensure better integration with existing system.

If you wish to enable logging, you will need to install a package which contains an implementation of `Psr\Log\LoggerInterface`&#x20;

::::hint{type="info"}
While any class which implements the PSR Logger interface is supported, we recommend using the [Monolog](https://github.com/Seldaek/monolog) package, which is already present in many of the major frameworks.&#x20;

You can install this in your application via composer:

:::CodeblockTabs
Bash

```linux
composer require monolog/monolog
```
:::
::::

All services which interact with Klevu's APIs accept a logger instance via their constructor; the only other class which implements logging at time of writing is the `RequestBearerTokenProvider` , which generates an authentication token for indexing.

Note: *If you are integrating into a modern framework, you should implement this via your dependency injection system*

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Provider\RequestBearerTokenProvider;
use Klevu\PhpSDK\Service\Account\AccountFeaturesService;
use Klevu\PhpSDK\Service\Account\AccountLookupService;
use Klevu\PhpSDK\Service\Account\UpdateStoreFeedUrlService;
use Klevu\PhpSDK\Service\Analytics\CollectService as AnalyticsCollectService;
use Klevu\PhpSDK\Service\Indexing\AttributesService;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;
use Klevu\PhpSDK\Service\Indexing\BatchService;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a new logger instance, writing to the /app/logs directory
//  with separate files for debugging and errors-only
$logger = new Logger(
    name: 'app',
    handlers: [
        new StreamHandler('/app/logs/error.log', Logger::ERROR),
        new StreamHandler('/app/logs/debug.log', Logger::DEBUG),
    ],
);

// Account
$accountFeatureService = new AccountFeaturesService(
    logger: $logger,
);
$accountLookupService = new AccountLookupService(
    logger: $logger,
);
$updateStoreFeedUrlService = new UpdateStoreFeedUrlService(
    logger: $logger,
);

// Analytics
$collectService = new AnalyticsCollectService(
    logger: $logger,
);

// Indexing
$attributesService = new AttributesService(
    logger: $logger,
);
$batchService = new BatchService(
    logger: $logger,
);
$batchDeleteService = new BatchDeleteService(
    logger: $logger,
);
$requestBearerTokenProvider = new RequestBearerTokenProvider(
    logger: $logger,
);

```

Once implemented, you should start seeing PHP-SDK related logs written to the files specified when creating the Logger.

[title] Add, Update, or Delete Indexing Attributes
[path] Examples / How To/Data Indexing/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Add or Update Attributes

:::hint{type="info"}
The following instructions are applicable to both Add and Update operations. When data is sent to Klevu's APIs, an attribute will be updated if it already exists and created otherwise.

Attributes are identified via the `attributeName` property.&#x20;
**Important:** this field is case-insensitive, so if you already have an attribute named, for example, `foo` and send a request with the name `FOO`, the original attribute will be updated, however the name will remain lowercase.
:::

To add or update custom attributes used by Klevu's JSON Indexing service, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, create an `AttributeInterface` object populated with the data to persist. Note, while you can create this using `new Attribute`, it is recommended to use the `AttributeFactory` class for ease of development and future compatibility.

Finally, instantiate an `AttributeService` object and call the `put` method with the Attribute object, catching and handling any exceptions thrown during execution.

:::hint{type="warning"}
If the attribute you are attempting to send is tagged as immutable ( `AttributeInterface::isImmutable()`), the SDK will prevent PUT operations during validation.
In this case, disabling the immutable flag and sending will cause the API to reject the request and the SDK to throw a `BadRequestException`
:::

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Indexing\Attribute;
use Klevu\PhpSDK\Model\Indexing\AttributeFactory;
use Klevu\PhpSDK\Model\Indexing\DataType;
use Klevu\PhpSDK\Service\Indexing\AttributesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$attributeFactory = new AttributeFactory();
$attribute = $attributeFactory->create(
    data: [
        Attribute::FIELD_ATTRIBUTE_NAME => 'example_attribute',
        Attribute::FIELD_DATATYPE => DataType::MULTIVALUE,
        Attribute::FIELD_LABEL => [
            'default' => 'Example Attribute',
        ],
        Attribute::FIELD_SEARCHABLE => true,
        Attribute::FIELD_FILTERABLE => false,
        Attribute::FIELD_RETURNABLE => true,
        Attribute::FIELD_IMMUTABLE => false,
    ],
);

$attributesService = new AttributesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

$response = null;
try {
    $response = $attributesService->put(
        accountCredentials: $accountCredentials,
        attribute: $attribute,
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$persistedSuccessfully = $response?->isSuccess();
$messages = $response?->getMessages();
```

## Delete Attributes

### Delete By Name

To delete custom attributes used by Klevu's JSON Indexing service, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `AttributeService` object and call the `deleteByName` method with the attributeName of the record you wish to remove, catching and handling any exceptions thrown during execution.

:::hint{type="warning"}
If the attribute is marked as immutable in Klevu's indexes, sending a DELETE request will cause the API to reject the request and the SDK to throw a `BadRequestException`
:::

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Indexing\AttributesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$attributesService = new AttributesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

try {
    $response = $attributesService->deleteByName(
        accountCredentials: $accountCredentials,
        attributeName: 'example_attribute',
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$deletedSuccessfully = $response?->isSuccess();
$messages = $response?->getMessages();
```

### Delete Object

&#x20;Alternatively, if you have an `AttributeInterface` already created, you can pass this to `AttributeService::delete` which acts as a wrapper around `deleteByName`.

Attributes passed to `delete` only require an `attributeName` property, which is internally extracted and passed to `deleteByName` . As such, attributes marked as immutable ( `AttributeInterface::isImmutable` will **not** be rejected by the SDK's validation.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Indexing\Attribute;
use Klevu\PhpSDK\Model\Indexing\AttributeFactory;
use Klevu\PhpSDK\Service\Indexing\AttributesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$attributeFactory = new AttributeFactory();
$attributesService = new AttributesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

try {
    $response = $attributesService->delete(
        accountCredentials: $accountCredentials,
        attribute: $attributeFactory->create(
            data: [
                Attribute::FIELD_ATTRIBUTE_NAME => 'example_attribute',
            ],
        ),
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$deletedSuccessfully = $response?->isSuccess();
$messages = $response?->getMessages();
```

***

## Source Code Reference

- Api\Model\Indexing\\[AttributeInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/AttributeInterface.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Model\Indexing\\[Attribute](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/Attribute.php)
- Model\Indexing\\[AttributeFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/AttributeFactory.php)
- Model\Indexing\\[DataType](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/DataType.php)
- Service\Indexing\\[AttributesService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/AttributesService.php)


[title] Data Indexing
[path] Guide/Features/

The PHP-SDK communicates with the JSON API (Klevu Indexing v2) only, information about which can be found in the [Data Indexing section of our documentation](https://docs.klevu.com/indexing-apis/JSON). Legacy XML-based indexing is not supported.

Services are provided to interact with both the Attributes API, in order to register additional data prior to data sync, and the Batch API, in order to send catalog data for indexing.

[title] Request Headers
[path] Guide/Technical / Architecture/

## User Agent

Requests sent to the Klevu APIs from the PHP-SDK contain a dynamic User-Agent value identifying the version of the php-sdk library used to transmit data, along with other relevant system information.

The purpose of this data is to aid in troubleshooting activities, as well as informing future product decisions.

By default, the library includes the version of the PHP-SDK library and PHP version running on the server. Example string: `klevu-php-sdk/1.0.0.0 (PHP 8.1.999)`.

Implementing systems may add additional data using additional provider classes via dependency injection. Examples of this can be found under [Examples / How To > Modify User-Agent in Request Headers](docId:23d-wcjHPN-2E_M-jQPfK)

[title] Account Management
[path] Guide/Features/

The PHP-SDK provides means of retrieving information about your Klevu account for use within your app. Via the account services , you can

- Generate an Account object containing account information and URL endpoints
- Query features enabled on your account
- Update the URL used by our indexer to download an XML feed of your catalog \[**Shopify and Bigcommerce customers only**]

## Retrieving Klevu Account Information

The AccountLookupService will query the `api.ksearchnet.com/user-account/public/platform/account/details` endpoint using your JS API Key and REST AUTH Key (available via Store Settings in KMC) and return an Account object. The Account object will provide the following information

| Property                        | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `jsApiKey`                      | Your unique public key<br />Example: `"klevu-1234567890"`                                                           |
| `restAuthKey`                   | Your private key, used to authenticate your account<br />Example: `"ABCDE1234567890"`                               |
| `platform`                      | The platform or framework your account is regstered to integrate with<br />Example: `"magento"`                     |
| `active`                        | Whether this account is currently active<br />Example: `true`                                                       |
| `companyName`                   | The company name entered when signing up to KMC<br />Example: `"Klevu"`                                             |
| `email`                         | The primary email address registered for this account<br />Example: `"contact@klevu.com"`                           |
| `indexingUrl`                   | Domain used to send data for indexing<br />Example: `"indexing.ksearchnet.com"`                                     |
| `searchUrl`                     | Domain used to perform searches on indexed data<br />Example: `"eucs27v2.ksearchnet.com"`                           |
| `smartCategoryMerchandisingUrl` | Domain used to perform Smart Category Merchandising queries on indexed data<br />Example: `"cn27v2.ksearchnet.com"` |
| `analyticsUrl`                  | Domain used to send analytics events<br />Example: `"stats.ksearchnet.com"`                                         |
| `jsUrl`                         | Domain used to embed Klevu-hosted JavaScript asssets<br />Example: `"js.klevu.com"`                                 |
| `tiersUrl`                      | Domain used to retrieve features information for a Klevu account<br />Example: `"tiers.klevu.com"`                  |

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure
- Requests returning a 401 status code from Klevu throw an `AccountNotFoundException`
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level

*More information and code samples can be found under&#x20;*[Examples / How To > Account Management > Retrieve Klevu Account Details](docId:1t7gUNUfpS0b-ICOkGwAr)

## Querying Enabled Features for Account

The AccountFeaturesService will query the Tiers endpoint and return an AccountFeatures object containing flags for features enabled on your Klevu account.&#x20;
An AccountFeatures object can also be attached to Account objects, and access via the `Account::getAccountFeatures()` method.

The following feature flags are available:

| Flag                         | Description                                                                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `smartCategoryMerchandising` | Whether the [Smart Category Merchandising](https://www.klevu.com/solutions/category-merchandising/) solution is available on this account |
| `smartRecommendations`       | Whether the [Product Recommendations](https://www.klevu.com/solutions/product-recommendations/) solution is available on this account     |
| `preserveLayout`             | Whether Preserve Layout should be available as a frontend layout option for integrations using this account                               |

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level
- Requested flags missing from, or unknown flags encountered within, the response are logged at `WARNING` level

*More information and code samples can be found under&#x20;*[Examples / How To > Account Management > Retrieve Klevu Account Details](docId:1t7gUNUfpS0b-ICOkGwAr)

## Updating the Store Feed Endpoint

:::hint{type="warning"}
**Note**: only available for accounts registered to integrate with Shopify or Bigcommerce stores
:::

The URL used by Klevu's indexing service to download and process catalog feeds in XML format can be modified using the UpdateStoreFeedUrlService. URL updates will take effect the next time Klevu's Feed Monitor service performs a scheduled sync.

To update the feed URL value for your account, you will need

- Your JS API and REST AUTH keys
- The platorm for which your account was registered (eg "shopify")
- The base URL associated with your Klevu account
- The full URL from which XML feeds can be downloaded

### Validation and Exception Handling

- Prior to transmitting data, the provided account credentials are validated as not empty and correctly formatted, throwing a `ValidationException` on failure
- Request exceptions, or responses identifying an invalid request throw a`BadRequestException`
- Client or Network exceptions, responses with unexpected status codes, or responses with a missing or invalid body content throw a `BadResponseException`

### Logging

- Request headers and body are logged prior to send at `DEBUG` level
- Response headers, body, and execution time are logged on successful request send at `DEBUG` level
- Requested flags missing from, or unknown flags encountered within, the response are logged at `WARNING` level

*More information and code samples can be found under&#x20;*[Examples / How To > Account Management > Update Store Feed Endpoint](docId\:GkiS-qMoZN9nU2WKWgrqO)

[title] Send Records for Indexing
[path] Examples / How To/Data Indexing/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Indexing Record Batches

To send batches of records to Klevu's indexer, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, extract the catalog information (eg, products; categories; custom entities) to be sent from your application, including all applicable variants if you are using complex products. As each system differs in storage and retrieval of data, the examples below simply contain hardcoded data.

:::hint{type="warning"}
As records of all types (KLEVU\_PRODUCT, KLEVU\_CATEGORY, etc) share an ID pool, you should implement a naming convention to differentiate records whose IDs would otherwise clash (for example, sending a product and a category, both with ID 1)
:::

Instantiate a new `RecordIterator` object and populate with `RecordInterface` items. Note, while you can create these using `new Record`, it is recommended to use the `RecordFactory` class for ease of development and future compatibility.

Finally, create a new `Indexing\BatchService` object and call the `send` method with the Record collection, catching and handling any exception thrown during execution.

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Indexing\RecordFactory;
use Klevu\PhpSDK\Model\Indexing\RecordIterator;
use Klevu\PhpSDK\Service\Indexing\BatchService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$recordFactory = new RecordFactory();
$records = new RecordIterator(
    data: [
        $recordFactory->create(
            data: [
                'id' => '1',
                'type' => 'KLEVU_PRODUCT',
                'relations' => [
                    'categories' => [
                        'values' => [
                            'category_1',
                        ],
                    ],
                ],
                'attributes' => [
                    'name' => [
                        'default' => 'Parent Product',
                    ],
                    'sku' => 'PARENT_PRODUCT',
                    'images' => [
                        [
                            'url' => 'https://www.klevu.com/parent-product.jpg',
                            'type' => 'default',
                        ],
                    ],
                    'prices' => [
                        [
                            'amount' => 42.0,
                            'currency' => 'GBP',
                            'type' => 'defaultPrice',
                        ],
                        [
                            'amount' => 10.0,
                            'currency' => 'GBP',
                            'type' => 'salePrice',
                        ],
                        [
                            'amount' => 3.14,
                            'currency' => 'GBP',
                            'type' => 'startPrice',
                        ],
                        [
                            'amount' => 50.0,
                            'currency' => 'GBP',
                            'type' => 'endPrice',
                        ],
                    ],
                    'url' => 'https://www.klevu.com/parent-product',
                    'inStock' => true,
                    'shortDescription' => [
                        'default' => 'Comfortable Chair',
                    ],
                    'description' => [
                        'default' => 'This is a very very comfortable chair',
                    ],
                ],
            ],
        ),      
        $recordFactory->create(
            data: [
                'id' => '2',
                'type' => 'KLEVU_PRODUCT',
                'relations' => [
                    'parentProduct' => [
                        'values' => [
                            '1',
                        ],
                    ],
                ],
                'attributes' => [
                    'name' => [
                        'default' => 'Variant Product',
                    ],
                    'sku' => 'VARIANT_PRODUCT',
                    'images' => [
                        [
                            'url' => 'https://www.klevu.com/variant-product.jpg',
                            'type' => 'default',
                        ],
                    ],
                    'prices' => [
                        [
                            'amount' => 42.0,
                            'currency' => 'GBP',
                            'type' => 'defaultPrice',
                        ],
                        [
                            'amount' => 3.14,
                            'currency' => 'GBP',
                            'type' => 'salePrice',
                        ],
                    ],
                    'url' => 'https://www.klevu.com/variant-product',
                    'inStock' => true,
                ],
            ],
        ),
    ],
);
$records->addItem(
    item: $recordFactory->create(
        data: [
            'id' => 'category_1',
            'type' => 'KLEVU_CATEGORY',
            'attributes' => [
                'name' => [
                    'default' => 'Example Category',
                ],
                'url' => 'https://www.klevu.com/simple-product',
                'categoryPath' => 'Foo/Bar',
            ],
        ],
    ),
);

$batchService = new BatchService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
    //  as well as behaviour config, such as invalidRecordMode
);

$response = null;
try {
    $response = $batchService->send(
        accountCredentials: $accountCredentials,
        records: $records,
    );
} catch (ValidationException $exception) {
    // One or more passed arguments are invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$sentSuccessfully = $response?->isSuccess() ?: false;
$messages = $response?->getMessages() ?: [];
```

### Handling Invalid Records

Prior to send, the PHP-SDK will validate each record in the provided batch. If any record fails this initial validation check, it will be removed from the batch to be sent. If removing invalid records leads to an empty batch, a `ValidationException` will be thrown and no API call will be attempted.

:::hint{type="warning"}
Note, the API may still reject an entire batch based upon the validity of a single record. In this instance, the operation will throw a `BadRequestException` . This behaviour cannot be changed via the SDK.
:::

To change the default behaviour and cause the internal validation to fail if *any* record is invalid, you can pass a flag to the BatchService during instantiation.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Service\Indexing\InvalidRecordMode
use Klevu\PhpSDK\Service\Indexing\BatchService;

// Invalid records will be removed from a batch. 
//   Processing will continue for any valid records remaining.
// Default behaviour
$batchService = new BatchService(
    invalidRecordMode: InvalidRecordMode::SKIP,
);

// Presence of an invalid record will cause the entire batch
//   to be rejected prior to processing.
$batchService = new BatchService(
    invalidRecordMode: InvalidRecordMode::FAIL,
);
```

***

## Source Code Reference

- Api\Model\\[Indexing\RecordInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/RecordInterface.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Model\\[Indexing\Record](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/Record.php)
- Model\\[Indexing\RecordFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordFactory.php)
- Model\\[Indexing\RecordIterator](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordIterator.php)
- Service\\[Indexing\BatchService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/BatchService.php)




[title] Delete Records from Index
[path] Examples / How To/Data Indexing/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Deleting Records from Index

### Delete By ID

To delete records from the Klevu indexes, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, retrieve the IDs used to index any records you wish to delete.

:::hint{type="warning"}
**Important**: the ID must match the value used when adding the record initially.&#x20;

As records of all types (KLEVU\_PRODUCT, KLEVU\_CATEGORY, etc) share an ID pool, you should implement a naming convention to differentiate records whose IDs would otherwise clash (for example, sending a product and a category, both with ID 1)
:::

Create a new `Indexing\Batch\DeleteService` object and call the `sendByIds` method with the array of IDs collated previously, catching and handling any exceptions thrown during execution.

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$batchDeleteService = new BatchDeleteService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
    //  as well as behaviour config, such as invalidRecordMode
);

$response = null;
try {
    $response = $batchDeleteService->sendByIds(
        accountCredentials: $accountCredentials,
        recordIds: [
            '1',
            '2',
            'category_1',
        ],
    );
} catch (ValidationException $exception) {
    // One or more passed arguments are invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$deletedSuccessfully = $response?->isSuccess();
$messages = $response?->getMessages();
```

### Delete Objects

Alternatively, if you `RecordInterface`(s) already created, you can pass these to `Batch\DeleteService::send` . Records passed to `send` only require an `id` property.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Indexing\RecordFactory;
use Klevu\PhpSDK\Model\Indexing\RecordIterator;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$recordFactory = new RecordFactory();
$records = new RecordIterator(
    data: [
        $recordFactory->create(['id' => '1']),
        $recordFactory->create(['id' => '2']),
        $recordFactory->create(['id' => 'category_1']),
    ],
);

$batchDeleteService = new BatchDeleteService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
    //  as well as behaviour config, such as invalidRecordMode or maxBatchSize
);

$response = null;
try {
    $response = $batchDeleteService->send(
        accountCredentials: $accountCredentials,
        records: $records,
    );
} catch (ValidationException $exception) {
    // One or more passed arguments are invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$deletedSuccessfully = $response?->isSuccess();
$messages = $response?->getMessages();
```

***

## Source Code Reference

- Api\Model\\[Indexing\RecordInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/RecordInterface.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Model\\[Indexing\Record](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/Record.php)
- Model\\[Indexing\RecordFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordFactory.php)
- Model\\[Indexing\RecordIterator](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordIterator.php)
- Service\\[Indexing\Batch\DeleteService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/Batch/DeleteService.php)


[title] Introduction
[path] /

&#x20;The Klevu PHP-SDK is a public library you can utilise in your PHP projects to handle common interactions with Klevu services, without having to reinvent the wheel.

The library is designed to be simple enough to get up and running quickly, but extensible enough to allow you to tailor to your site and platform's specific needs.

## Getting Started

1. [Create an account with Klevu](https://box.klevu.com/merchant/signup).
   *Free trial, with full access to all features is available.*
2. Retrieve your **JS API Key** and **REST AUTH Key** from Store Settings > Store Info in your account.
3. **Install the SDK** in your application using composer.

```shell
composer require klevu/php-sdk
```

:FontAwesome[]{icon="fa-brands fa-github"} You can also browse and download the source code from github at <font color="#eb144c"></font>&#x20;

## System Requirements

To use this library, you must be running a support version of PHP (8.1+) compiled with the libxml and simplexml extensions.
See the [PHP docs](https://www.php.net/manual/en/simplexml.installation.php) for more information.

You will also require a [PSR-18 compatible](https://www.php-fig.org/psr/psr-18/) HTTP client, such as guzzlehttp/guzzle,
which provides psr/http-client-implementation support.
A [list of compatible libraries can be found on Packagist](https://packagist.org/providers/psr/http-client-implementation).

We also recommend a [PSR-3 compatible](https://www.php-fig.org/psr/psr-3/) logger library, such as monolog/monolog.
This will allow the SDK to write activity it performs to a location of your choice.

[title] Features
[path] Guide/


[title] Data Indexing
[path] Examples / How To/


[title] Modify User-Agent In Request Headers
[path] Examples / How To/

## Introduction

The `UserAgentProvider` is responsible for collating and returning all configured components separated by a space character. This class is a composite provider, that can be configured via DI to inject additional providers into the constructor which are included in the `User-Agent` header value used in API calls.

There should be no need to replace this class with your own implementation, and doing so may break other packages which inject their own providers. Instead, create additional class(es) implementing the `UserAgentProviderInterface` which return the user agent information (either new components or additional information for an existing component, where supported).

## Inject Additional Components

First, create a new class which implements `Provider\UserAgentProviderInterface` and add the `execute` method, returning the desired string.

:::hint{type="info"}
If you wish to allow other modules to inject their own system information into your component, you can should implement the `Provider\ComposableUserAgentProviderInterface` interface, which extends the base interface.
You can also use the`Provider\ComposableUserAgentProviderTrait` to include implementation of child providers.
:::



:::CodeblockTabs
Basic

```php
<?php

declare(strict_types=1);

namespace Acme\MyModule\Provider\UserAgent;

use Klevu\PhpSDK\Provider\UserAgentProviderInterface;

class PhpSDKUserAgentProvider implements UserAgentProviderInterface
{
    /**
     * @return string
     */
    public function execute(): string
    {
        return 'MyModule/1.0.0';
    }
}

```

Composable

```php
<?php

declare(strict_types=1);

namespace Acme\MyModule\Provider\UserAgent;

use Klevu\PhpSDK\Provider\ComposableUserAgentProviderInterface;
use Klevu\PhpSDK\Provider\ComposableUserAgentProviderTrait;
use Klevu\PhpSDK\Provider\UserAgentProviderInterface;

class MyUserAgentProvider implements ComposableUserAgentProviderInterface
{
    use ComposableUserAgentProviderTrait;

    /**
     * @param array<string, UserAgentProviderInterface> $systemInformationProviders
     */
    public function __construct(
        array $systemInformationProviders,
    ) {
        array_walk(
            array: $systemInformationProviders,
            callback: function (mixed $systemInformationProvider, int|string $identifier): void {
                $this->addUserAgentProvider(
                    userAgentProvider: $systemInformationProvider,
                    identifier: $identifier,
                );
            },
        );
    }
    
    /**
     * @return string
     */
    public function execute(): string
    {
        return sprintf(
            'MyModule/1.0.0 (%s)',
            implode(
                separator: ' ',
                array: array_map(
                    callback: static fn (UserAgentProviderInterface $systemInformationProvider): string => (
                        $systemInformationProvider->execute()
                    ),
                    array: $this->userAgentProviders, 
                ),
            ),
        );
    }
}

```
:::

Once you have your user agent provider, create a new instance of `UserAgentProvider` and inject it into the constructor.&#x20;
Note: *If you are integrating into a modern framework, you should implement this via your dependency injection system*

This User Agent Provider instance can then be passed into any service which interacts with Klevu's APIs

```php
<?php

declare(strict_types=1);

use Acme\MyModule\Provider\UserAgent\MyUserAgentProvider;
use Klevu\PhpSDK\Provider\UserAgentProvider;
use Klevu\PhpSDK\Service\Account\AccountFeaturesService;
use Klevu\PhpSDK\Service\Account\AccountLookupService;
use Klevu\PhpSDK\Service\Account\UpdateStoreFeedUrlService;
use Klevu\PhpSDK\Service\Analytics\CollectService as AnalyticsCollectService;
use Klevu\PhpSDK\Service\Indexing\AttributesService;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;
use Klevu\PhpSDK\Service\Indexing\BatchService;

$userAgentProvider = new UserAgentProvider(
    userAgentProviders: [
        new MyUserAgentProvider(),
    ],
);

// Or, if using the composable templates

$userAgentProvider = new UserAgentProvider(
    userAgentProviders: [
        new MyUserAgentProvider(
            systemInformationProviders: [
                new MySystemInformationProvider(),
            ],
        ),
    ],
);

// Account
$accountFeatureService = new AccountFeaturesService(
    userAgentProvider: $userAgentProvider,
);
$accountLookupService = new AccountLookupService(
    userAgentProvider: $userAgentProvider,
);
$updateStoreFeedUrlService = new UpdateStoreFeedUrlService(
    userAgentProvider: $userAgentProvider,
);

// Analytics
$collectService = new AnalyticsCollectService(
    userAgentProvider: $userAgentProvider,
);

// Indexing
$attributesService = new AttributesService(
    userAgentProvider: $userAgentProvider,
);
$batchService = new BatchService(
    userAgentProvider: $userAgentProvider,
);
$batchDeleteService = new BatchDeleteService(
    userAgentProvider: $userAgentProvider,
);
```

In the above scenario, the expected user agent string result would look like
`klevu-php-sdk/0.0.0.1 (PHP 8.1.999) MyModule/1.0.0`
or, if composble
`klevu-php-sdk/0.0.0.1 (PHP 8.1.999) MyModule/1.0.0 (MySystem)`

***

## Source Code Reference

- Provider\\[ComposableUserAgentProviderInterface](https://github.com/klevu/php-sdk/blob/master/src/Provider/ComposableUserAgentProviderInterface.php)
- Provider\\[ComposableUserAgentProviderTrait](https://github.com/klevu/php-sdk/blob/master/src/Provider/ComposableUserAgentProviderTrait.php)
- Provider\\[UserAgentProvider](https://github.com/klevu/php-sdk/blob/master/src/Provider/UserAgentProvider.php)
- Provider\\[UserAgentProviderInterface](https://github.com/klevu/php-sdk/blob/master/src/Provider/UserAgentProviderInterface.php)


[title] Dependencies and Auto-Discovery
[path] Guide/Technical / Architecture/

The PHP-SDK is designed to be as interoperable as possible. As such, dependencies on third party libraries - especially where alternatives exist - is kept to a minimum, and required versions kept as loose as possible.

## Existing Dependencies

| Package                                   | Details                                                                                                                                                                                          |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `php`                                     | All [currently maintained (including security support) PHP versions](https://www.php.net/supported-versions.php) are supported.                                                                  |
| `ext-libxml`<br />`ext-simplexml`         | XML handling libraries are required to process the response payload of some Klevu APIs                                                                                                           |
| `psr/log`                                 | Allows hooking in [PSR-3 compliant logging](https://www.php-fig.org/psr/psr-3/)                                                                                                                  |
| `psr/http-client`<br />`psr/http-message` | Allows hooking in [PSR-17 compliant HTTP factories](https://www.php-fig.org/psr/psr-17/) and [PSR-18 compliant HTTP clients](https://www.php-fig.org/psr/psr-18/) to communicate with Klevu APIs |
| `php-http/discovery`                      | Provides auto-discovery functionality for compatible HTTP clients and factories already installed in your application                                                                            |

## Auto-Discovery

### HTTP Client, Request and Response Factories

In order to reduce installation time in applications which already have a PSR-18 compliant HTTP client, such as Guzzle, any class which needs to communicate with the Klevu APIs will attempt to automatically discover a suitable client for transport. This action occurs during object instantiation and will throw an exception if a class cannot be found.
If your application uses a non-PSR-18 compliant library or PHP's curl functions directly, you will need to install or create a client which implements `Psr\Http\Client\ClientInterface` and ensure they are available to your autoloader.

The HTTP Discovery package will also attempt to locate factory classes responsible for creating PSR-17-compliant Request and Response objects.
If your application does not contain these factories, you will need to install or create classes which implement `Psr\Http\Message\RequestFactoryInterface` and `Psr\Http\Message\ResponseFactoryInterface` and ensure they are available to your autoloader.

:::hint{type="info"}
If automatic discovery cannot locate implementations of any of the above classes, or you wish to use a different class to the one found, all service classes will allow injection of the relevant classes through the constructor.
:::

For more information and examples, please see the [Configure HTTP Transport](docId\:Waa8UvHYbJ_om0CYK00EA) How-To article.

### Logging

As logging is not an integral component of the SDK, it will not attempt auto-discovery for implementations of `Psr\Log\LoggerInterface` . In this scenario, no errors will be raised - logging will be silently skipped.&#x20;

To enable logging, you should install or create an implementation of a PSR-3 compliant logger and inject it manually into the applicable classes.&#x20;

For more information and examples, please see the [Logging](docId\:He6HsiAm09aDhe9F0iNsH) How-To article.

[title] Update Store Feed Endpoint (Shopify / Bigcommerce)
[path] Examples / How To/Account Management/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="warning"}
This guide is applicable to Shopify and Bigcommerce stores only. Before making changes to your feed endpoint, please [consult with our support team](https://help.klevu.com/support/tickets/new).
:::

## Updating Store Feed Endpoint

To update the endpoint used by Klevu's XML Feed Monitoring service, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `UpdateStoreFeedUrlService` object and call the `execute` method with the following information

- Account credentials retrieved above
- The full URL which should be used to download your XML feed
- The store type (from the `Platforms` enum options)
- The URL used to register your account
  *Note: the domain should contain either&#x20;*`.myshopify.com`*&#x20;or&#x20;*`.mybigcommerce.com`

This call will throw exceptions if any issues arise, so you should catch and handle these appropriately.

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Platforms;
use Klevu\PhpSDK\Service\Account\UpdateStoreFeedUrlService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);
$updateStoreFeedUrlService = new UpdateStoreFeedUrlService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

$response = null;
try {
    $response = $updateStoreFeedUrlService->execute(
        accountCredentials: $accountCredentials,
        indexingUrl: 'https://www.example.com/feed.xml',
        storeType: Platforms::SHOPIFY->value, // "shopify"
        storeUrl: 'https://example.myshopify.com',
    );
} catch (ValidationException $exception) {
    // One or more supplied arguments are missing or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$updatedSuccessfully = $response?->isSuccess() ?: false;
$messages = $response?->getMessages() ?: [];
```

***

## Source Code Reference

- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Model\\[Platforms](https://github.com/klevu/php-sdk/blob/master/src/Model/Platforms.php)
- Service\Account\\[UpdateStoreFeedUrlService](https://github.com/klevu/php-sdk/blob/master/src/Service/Account/UpdateStoreFeedUrlService.php)








[title] Retrieve Klevu Account Details
[path] Examples / How To/Account Management/

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Retrieving Klevu Account Information

To retrieve information about your Klevu account, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `AccountLookupService` object and call the `execute` method to create an Account model containing your account details.
The `execute` method will throw exceptions if any issues arise, so you should catch and handle these appropriately.

At this point, you will have an Account object containing your KMC information, including endpoints which can be used for subsequent operations (such as indexing or analytics)

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\AccountNotFoundException;
use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Account\AccountLookupService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);
$accountLookupService = new AccountLookupService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

$account = null;
try {
    $account = $accountLookupService->execute($accountCredentials);
} catch (ValidationException $exception) {
    // Account credentials are empty or invalid
} catch (AccountNotFoundException $exception) {
    // No account exists for JS API Key / REST AUTH Key combination
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}
```

## Retrieving Enabled Klevu Feature Flags

To retrieve information about your Klevu account, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, instantiate an `AccountFeaturesService` object and call the `execute` method to create an `AccountFeatures` model containing Klevu feature flags.
The `execute` method will throw exceptions if any issues arise, so you should catch and handle these appropriately.

At this point, you will have an Account Features object which can be used to determine which solutions should be supported in your application.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Service\Account\AccountFeaturesService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);
$accountFeaturesService = new AccountFeaturesService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
);

$account = null;
try {
    $accountFeatures = $accountFeaturesService->execute($accountCredentials);
} catch (ValidationException $exception) {
    // Account credentials are empty or invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}
```

For ease in use in your application, you can also attach the Account Features object to an existing Account model for ease of reference in your application

```php
<?php

// snip

$account = null;
try {
    $account = $accountLookupService->execute($accountCredentials);
    $account->setAccountFeatures(
        $accountFeaturesService->execute($accountCredentials),
    );
} catch (ValidationException $exception) {
    // Account credentials are empty or invalid
} catch (AccountNotFoundException $exception) {
    // No account exists for JS API Key / REST AUTH Key combination
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

// Get feature flags
$categoryMerchandisingEnabled = $account->getAccountFeatures()->smartCategoryMerchandising;
```

***

## Source Code Reference

- Exception\\[AccountNotFoundException](https://github.com/klevu/php-sdk/blob/master/src/Exception/AccountNotFoundException.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[Account](https://github.com/klevu/php-sdk/blob/master/src/Model/Account.php)
- Model\Account\\[AccountFeatures](https://github.com/klevu/php-sdk/blob/master/src/Model/Account/AccountFeatures.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Service\Account\\[AccountFeaturesService](https://github.com/klevu/php-sdk/blob/master/src/Service/Account/AccountFeaturesService.php)
- Service\Account\\[AccountLookupService](https://github.com/klevu/php-sdk/blob/master/src/Service/Account/AccountLookupService.php)


[title] Configure HTTP Transport
[path] Examples / How To/

The PHP-SDK does not specify a dependency on any HTTP client to ensure better integration with existing systems and frameworks. Instead, the [PHP HTTP Discovery package](https://github.com/php-http/discovery) is used to allow us to detect a [compatible HTTP client](https://github.com/php-fig/http-client/blob/master/src/ClientInterface.php) where required.

::::hint{type="info"}
If your application does not already use a [PSR-18 compatible](https://www.php-fig.org/psr/psr-18/) client, you will need to install one before sending data to Klevu's APIs. We recommend using [Guzzle](https://github.com/guzzle/guzzle/), which can be installed with the following command

:::CodeblockTabs
Bash

```linux
composer install guzzlehttp/guzzle
```
:::
::::

All services which interact with Klevu's APIs accept a HTTP client instance via their constructor.

Note: *If you are integrating into a modern framework, you should implement this via your dependency injection system even if automatic discovery succeeds to ensure better stability and application performance.*

```php
<?php

declare(strict_types=1);

use GuzzleHttp\Client;
use Klevu\PhpSDK\Service\Account\AccountFeaturesService;
use Klevu\PhpSDK\Service\Account\AccountLookupService;
use Klevu\PhpSDK\Service\Account\UpdateStoreFeedUrlService;
use Klevu\PhpSDK\Service\Analytics\CollectService as AnalyticsCollectService;
use Klevu\PhpSDK\Service\Indexing\AttributesService;
use Klevu\PhpSDK\Service\Indexing\Batch\DeleteService as BatchDeleteService;
use Klevu\PhpSDK\Service\Indexing\BatchService;

$httpClient = new Client();

// Account
$accountFeatureService = new AccountFeaturesService(
    httpClient: $httpClient,
);
$accountLookupService = new AccountLookupService(
    httpClient: $httpClient,
);
$updateStoreFeedUrlService = new UpdateStoreFeedUrlService(
    httpClient: $httpClient,
);

// Analytics
$collectService = new AnalyticsCollectService(
    httpClient: $httpClient,
);

// Indexing
$attributesService = new AttributesService(
    httpClient: $httpClient,
);
$batchService = new BatchService(
    httpClient: $httpClient,
);
$batchDeleteService = new BatchDeleteService(
    httpClient: $httpClient,
);
```


[space] Template JS (/template-js)

[title] Add Pagination To URL
[path] How To/



There are times when it is beneficial to have the users selected pagination captured and stored as part of the URL.

For Example :

- Allow for consistent tracking of the selected page of results.
- Reusable 'landing  page' links
- SEO

To accomplish this we will add in a custom override module that will:

1. Intercept the outgoing query
2. Analyze the existing URL string
3. Update the localstorage of selected page value
4. Apply the page offset to the outgoing query
5. Update the existing URL string

See : [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu JS overriding


## Template JS Override

Add the supporting module `addPaginationToURL` and apply it to the landing page override.

**Note :** the same `addPaginationToURL` module can be used on Category pages by applying the override to the `catnav` scope as well.

**Full Example**

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">

klevu.modifyRequest("landing,catnav", function(data, scope){
    // Apply the selected page value from the current URL string            
    klevu.search.modules.addPaginationToURL.base.getAndUpdatePagination(data, scope);
});

klevu.afterTemplateRender("landing,catnav", function(data, scope){
    // Add selected page value to the URL string
    klevu.search.modules.addPaginationToURL.base.setPagination(data, scope);
});

</script>

<script type="text/javascript">

// addPaginationToURL module
(function(klevu) {
  klevu.extend(true, klevu.search.modules, {
      addPaginationToURL: {
          base: {
              setPagination: function(data, scope, queryId) {
                  var hasPaginationEnabled = klevu.getSetting(klevu, "settings.theme.modules.pagination.searchResultsPage.enable");
                  if (hasPaginationEnabled === true) {
                      var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                      if (queryId && queryId.length) {
                          activeQueryId = queryId;
                      }
                      var paginationQueryParam = activeQueryId + "PgNo";
                      var activeQueryMeta = klevu.getObjectPath(data, "template.query." + activeQueryId + ".meta");
                      var paginationValuesQueryParam = 0;
                      if (activeQueryMeta) {
                          var productListLimit = activeQueryMeta.noOfResults;
                          paginationValuesQueryParam = Math.ceil(activeQueryMeta.offset / productListLimit) + 1;
                      }
                      var searchPath = window.location.search;
                      var updatedPath;
                      
                      // write to the URL if we're on page 2 or above
                      if (paginationValuesQueryParam > 1) {
                          updatedPath = klevu.dom.helpers.updateQueryStringParameter(searchPath, paginationQueryParam, paginationValuesQueryParam);

                      // otherwise remove the pagination from URL
                      } else {
                          updatedPath = searchPath.replace(new RegExp('[?&]' + paginationQueryParam + '=[^&]*'), '');
                          if (updatedPath.charAt(0) === '&') {
                              updatedPath = '?' + updatedPath.substring(1);
                          }
                      }
                      
                      if ('undefined' !== typeof window.history && 'undefined' !== typeof window.history.replaceState) {
                          window.history.replaceState({}, "", updatedPath);
                      } else {
                          console.log("This browser does not have the support of window.history or window.history.replaceState");
                      }
                  }
              },
              getAndUpdatePagination: function(data, scope, queryId) {
                  var hasAlreadyTriggered = klevu.getObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered");
                  if (hasAlreadyTriggered === true) {
                      return;
                  }
                  var matchedQueryParamId = ""
                    , matchedQueryParamValue = "";
                  var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                  if (recordQueries && recordQueries.length) {
                      klevu.each(recordQueries, function(key, query) {
                          if (query.id) {
                              var paginationFromURL = klevu.dom.helpers.getQueryStringValue(query.id + "PgNo");
                              if (paginationFromURL && paginationFromURL.length) {
                                  matchedQueryParamId = query.id;
                                  matchedQueryParamValue = paginationFromURL;
                              }
                          }
                      })
                  }
                  klevu.setObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered", true);
                  var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                  if (queryId && queryId.length) {
                      activeQueryId = queryId;
                  } else if (matchedQueryParamId.length && matchedQueryParamValue.length) {
                      activeQueryId = matchedQueryParamId;
                      var storage = klevu.getSetting(scope.kScope.settings, "settings.storage");
                      if (storage.tabs) {
                          storage.tabs.setStorage("local");
                          storage.tabs.mergeFromGlobal();
                          storage.tabs.addElement("active", activeQueryId);
                          storage.tabs.mergeToGlobal();
                      }
                  }
                  var paginationQueryParam = activeQueryId + "PgNo";
                  var paginationFromURL = klevu.dom.helpers.getQueryStringValue(paginationQueryParam);
                  paginationFromURL = Number(paginationFromURL);
                  if (paginationFromURL && paginationFromURL > 1) {
                      var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                      if (recordQueries.length) {
                          klevu.each(recordQueries, function(key, recordQuery) {
                              if (recordQuery.id === activeQueryId) {
                                  var limit = klevu.getObjectPath(recordQuery, "settings.limit");
                                  limit = Number(limit);
                                  if (limit > 0) {
                                      var expectedOffset = (paginationFromURL - 1) * limit;
                                      klevu.setObjectPath(data, "localOverrides.query." + activeQueryId + ".settings.offset", expectedOffset);
                                  }
                              }
                          });
                      }
                  }
              }
          },
          build: true
      }
  });
}
)(klevu);

</script>
```
:::


[title] Untitled
[path] Getting Started/


[title] Add Filters To URL
[path] How To/



There are scenarios when it is useful for the user selected filters and/or merchant preset filters to be captured as part of the SRLP  or Category URL.

For Example:

- Allow for consistent tracking of selected facets.
- Reusable 'landing page' links

To accomplish this we will add in a custom override module named **addFiltersToURL** that will:

1. Intercept the outgoing query&#x20;
2. Analyze the existing URL string
3. Update the localstorage of selected facets
4. Apply the necessary filters to the outgoing query
5. Update the existing URL string

See : Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) and Modify Response [Overview](docId\:k-USIa-fv-m380BqcAw7P) for details on Klevu JS overriding



## Template JS Override

Add the supporting module, `addFiltersToURL` and apply its use to the page overrides.

**Note :** The example is set for both Search (`landing`) and Category (`catnav`) scopes.



**Full Example**

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">

klevu.modifyRequest("landing,catnav", function(data, scope){
    // Apply the selected facets from the current URL string            
    klevu.search.modules.addFiltersToURL.base.getAndUpdateFilters(data, scope);

});

klevu.afterTemplateRender("landing,catnav", function(data, scope){
    // Add selected facets to the URL string
    klevu.search.modules.addFiltersToURL.base.setFilters(data, scope);

});

</script>




<script type="text/javascript">

/* Klevu addFiltersToURL Module */
    (function(klevu) {
    klevu.extend(true, klevu.search.modules, {
        addFiltersToURL: {
            base: {
                setFilters: function(data, scope, queryId) {
                    var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                    if (queryId && queryId.length) {
                        activeQueryId = queryId;
                    }
                    var filterQueryParam = activeQueryId + "Filters";
                    var activeQueryFilters = klevu.getObjectPath(data, "template.query." + activeQueryId + ".filters");
                    var filterValuesQueryParam = "";
                    if (activeQueryFilters) {
                        klevu.each(activeQueryFilters, function(key, filter) {
                            var selectedFilterKeyString = "";
                            var filterOptions = filter.options;
                            var selectedValues = "";
                            if (filterOptions && filterOptions.length) {
                                klevu.each(filterOptions, function(key, option) {
                                    if (option.selected === true) {
                                        if (selectedValues.length) {
                                            selectedValues += ",";
                                        }
                                        selectedValues += option.value;
                                    }
                                });
                            } else if (filter.type === "SLIDER") {
                                var startValue = filter.start;
                                var endValue = filter.end;
                                var minValue = filter.min;
                                var maxValue = filter.max;
                                if (typeof startValue !== "undefined" && startValue !== null && typeof endValue !== "undefined" && endValue !== null) {
                                    if (Number(startValue) === Number(minValue) && Number(endValue) === Number(maxValue)) {} else {
                                        selectedValues = startValue + "-" + endValue;
                                    }
                                }
                            }
                            if (selectedValues.length) {
                                selectedFilterKeyString += filter.key + ":" + selectedValues;
                            }
                            if (selectedFilterKeyString.length) {
                                if (filterValuesQueryParam.length) {
                                    filterValuesQueryParam += ";";
                                }
                                filterValuesQueryParam += selectedFilterKeyString;
                            }
                        });
                    }
                    var searchPath = window.location.search;
                    var updatedPath;
                    
                    if (filterValuesQueryParam.length) {
                        // Add or update the filter parameter when there are values
                        filterValuesQueryParam = encodeURIComponent(filterValuesQueryParam);
                        updatedPath = klevu.dom.helpers.updateQueryStringParameter(searchPath, filterQueryParam, filterValuesQueryParam);
                    } else {
                        // Remove the filter parameter when empty
                        updatedPath = klevu.dom.helpers.updateQueryStringParameter(searchPath, filterQueryParam, "");
                        updatedPath = updatedPath.replace("?" + filterQueryParam + "=&", "?");
                        updatedPath = updatedPath.replace("&" + filterQueryParam + "=", "");
                        updatedPath = updatedPath.replace("?" + filterQueryParam + "=", "");
                    }
                    
                    // Handle when no URL parameters are present
                    if (!updatedPath || updatedPath === "" || updatedPath === "?") {
                        updatedPath = window.location.pathname;
                    }
                    
                    if ('undefined' !== typeof window.history && 'undefined' !== typeof window.history.replaceState) {
                        window.history.replaceState({}, "", updatedPath);
                    } else {
                        console.log("This browser does not have the support of window.history or window.history.replaceState");
                    }
                },
                getAndUpdateFilters: function(data, scope, queryId) {
                    var hasAlreadyTriggered = klevu.getObjectPath(scope.kScope, "element.kScope.getAndUpdateFiltersTriggered");
                    if (hasAlreadyTriggered === true) {
                        return;
                    }
                    var matchedQueryParamId = ""
                        , matchedQueryParamValue = "";
                    var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                    if (recordQueries && recordQueries.length) {
                        klevu.each(recordQueries, function(key, query) {
                            if (query.id) {
                                var filtersFromURL = klevu.dom.helpers.getQueryStringValue(query.id + "Filters");
                                if (filtersFromURL && filtersFromURL.length) {
                                    matchedQueryParamId = query.id;
                                    matchedQueryParamValue = filtersFromURL;
                                }
                            }
                        })
                    }
                    klevu.setObjectPath(scope.kScope, "element.kScope.getAndUpdateFiltersTriggered", true);
                    var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                    if (queryId && queryId.length) {
                        activeQueryId = queryId;
                    } else if (matchedQueryParamId.length && matchedQueryParamValue.length) {
                        activeQueryId = matchedQueryParamId;
                        var storage = klevu.getSetting(scope.kScope.settings, "settings.storage");
                        if (storage.tabs) {
                            storage.tabs.setStorage("local");
                            storage.tabs.mergeFromGlobal();
                            storage.tabs.addElement("active", activeQueryId);
                            storage.tabs.mergeToGlobal();
                        }
                    }
                    var filterQueryParam = activeQueryId + "Filters";
                    var filtersFromURL = klevu.dom.helpers.getQueryStringValue(filterQueryParam);
                    if (filtersFromURL && filtersFromURL.length) {
                        var facets = filtersFromURL.split(";");
                        if (facets) {
                            klevu.each(facets, function(key, facet) {
                                var splitFacet = facet.split(":");
                                if (splitFacet.length) {
                                    var facetKey = splitFacet[0];
                                    var facetValues = splitFacet[1].split(",");
                                    var applyFilters = klevu.getObjectPath(data, "localOverrides.query." + activeQueryId + ".filters.applyFilters.filters");
                                    if (applyFilters && applyFilters.length) {
                                        var isExistingKey = false;
                                        klevu.each(applyFilters, function(key, applyFilter) {
                                            if (applyFilter.key === facetKey) {
                                                isExistingKey = true;
                                                klevu.each(facetValues, function(key, facetValue) {
                                                    var isFilterOptionMatched = false;
                                                    klevu.each(applyFilter.values, function(key, value) {
                                                        if (facetValue === value) {
                                                            isFilterOptionMatched = true;
                                                        }
                                                    });
                                                    if (!isFilterOptionMatched) {
                                                        applyFilter.values.push(facetValue);
                                                    }
                                                });
                                            }
                                        });
                                        if (!isExistingKey) {
                                            applyFilters.push({
                                                key: facetKey,
                                                values: facetValues
                                            });
                                        }
                                    } else {
                                        klevu.setObjectPath(data, "localOverrides.query." + activeQueryId + ".filters.applyFilters.filters", [{
                                            key: facetKey,
                                            values: facetValues
                                        }]);
                                    }
                                }
                            });
                        }
                    }
                }
            },
            build: true
        }
    });
    }
    )(klevu);

</script>

```
:::


[title] Voice Search
[path] How To/



Enable Klevu to use the browser's built-in microphone access to capture voice-dictated search queries

:::hint{type="warning"}
**Important :** Voice search is supported only in Google Chrome browser, version 26 and above and only works on HTTPS URLs.
:::



To get the best out of voice search, we advise enabling **Klevu's Advanced NLP** feature for your store. Enabling the Advanced NLP feature will ensure Klevu is able to understand and interpret long tail queries (i.e. anything beyond 5 words in a single query).&#x20;

If you are not sure whether you have this feature enabled or not, please [contact Klevu support](https://help.klevu.com/support/tickets/new)  for further assistance on this option.



## Display Options

The default display options can be customized using the below format:

:::BlockQuote
var klevu\_micOptions = \{
&#x20; micImage: "\<url-for-mic-image>",
&#x20; micAnimationImage: "\<url-for-mic-animation-image>",
&#x20; voiceSearchPlaceholder: "\<placeholder-message-for-voice-search>" &#x20;
&#x20;};
:::

CSS can be applied to further adjust display to fit your needs

:::BlockQuote
&#x20; \<style>
&#x20;   .klevuVoiceSearchImage \{
&#x20;     ...
&#x20;   }
&#x20; \</style>
:::

#

## Template JS implementation

The example below references an external reference to `klevu-voicesearch.js` that will tap into the browsers microphone access.

:::CodeblockTabs
JavaScript

```html
 <script type="text/javascript">
    /* required to accmodate Klevu Template JS */
    var klevu_layout = true;
  </script>

  <script type="text/javascript" src="https://js.klevu.com/klevu-js-v1/js/klevu-voicesearch.js"></script>

  <script type="text/javascript">
    (function () {
      /* example options modifications */
      var klevu_micOptions = {
        micImage: "https://js.klevu.com/klevu-js-v1/img-1-1/speech.png",
        micAnimationImage: "https://js.klevu.com/klevu-js-v1/img-1-1/mic-animate.gif",
        voiceSearchPlaceholder: "Listening..."
      };
      klevu_voiceSearch.init(klevu_micOptions);
    })();
  </script>
  <style>
    .klevuVoiceSearchImage {
      position: absolute;
      right: 34px;
      top: 50%;
      line-height: 24px;
      cursor: pointer;
      width: 24px;
      height: 24px;
      background: #ededed;
      border-radius: 50px;
      padding: 3px;
      margin-top: -12px;
      box-sizing: border-box;
    }
  </style>
```
:::

&#x20;

[title] Untitled
[path] Build UI/


[title] Styling CSS
[path] Build UI/Templates Customizations/



## Option 1: Override Klevu Styles (recommended)

The simplest, and our recommended approach to custom styling, is to override the base CSS rules. Create your own stylesheet, include it in your website and override the styles you would like to change by cross-referencing our base stylesheets.

With this approach, as Klevu introduces new features or bug fixes, we may tweak the base CSS and you will directly benefit from these fixes. We take care not to introduce any breaking changes, but this approach does mean that if you have overridden something which we change in our base file, you may need to make minor changes to your own overrides from time to time.

**Default CSS files**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-styles.css
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/landing-styles.css
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/catnav-styles.css
:::

:::hint{type="info"}
**Note:** You can place an additional **.debug** within the filename to view the un-minified version. This is handy for reference purposes only.
:::

e.g.

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-style&#x73;**.debug**.css
:::



## Option 2: Overwrite Klevu Styles

If you prefer to modify the styles directly, rather than creating overrides, you may wish to take a copy of our CSS file and create your own version. You can then add this to your website and modify any of our CSS rules in place.

In order to stop Klevu styles from loading, you will need to add a setting to Klevu initialization to prevent the loading of our default styles:

:::BlockQuote
klevu(\{
&#x20;       theme: \{
&#x20;           quickSearch: \{
&#x20;               loadDefaultStyles: false
&#x20;           },
&#x20;           landing: \{
&#x20;               loadDefaultStyles: false
&#x20;           },
&#x20;           catnav: \{
&#x20;               loadDefaultStyles: false
&#x20;           }
&#x20;       }
&#x20;});
:::



## Important note about Klevu Analytics classes

The Klevu Template JS includes the necessary analytics class selectors for reporting product click tracking.

**Including these specific class selectors is a common oversight when using custom templates.**

See  [Analytics/Tracking](docId\:RyZKC8NcV55-QcfjLuoHQ) for further details

[title] Configuration
[path] Library Reference/



Specific configuration values used by Klevu are kept as a snippet of code which looks something like the following:

:::BlockQuote

&#x20; var **options** = \{
&#x20;    url : \{
&#x20;      search: 'https\://eucs3v2.ksearchnet.com/cs/v2/search',
&#x20;      landing: '/search-results',
&#x20;      queryParam: 'q'
&#x20;    },
&#x20;    search: \{
&#x20;      apiKey: 'klevu-123XXXXXXXXXXXXXX',
&#x20;      searchBoxSelector: 'input#klevu-search',
&#x20;    }
&#x20;    analytics: \{
&#x20;      apiKey: 'klevu-123XXXXXXXXXXXXXX'
&#x20;    }
&#x20; };
&#x20; klevu(options);
&#x20;

:::



## Settings

Settings available within `options` object

| Object name                                    | Field Name                          | Description                                                                                                                                                                   | Default value                         |
| ---------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| powerUp                                        | quick                               | QuickSearch Module                                                                                                                                                            | true                                  |
| powerUp                                        | landing                             | Landing Page Module                                                                                                                                                           | true                                  |
| powerUp                                        | catnav                              | Category Page Module                                                                                                                                                          | true                                  |
| powerUp                                        | recsModule                          | Recommendations Module                                                                                                                                                        | true                                  |
| url                                            | search                              | Klevu APIv2 Cloud Search URL endpoint                                                                                                                                         | <font color="#3b9f0f">REQUIRED</font> |
| url                                            | landing                             | The URL of the Search Results Landing Page (SRLP)                                                                                                                             | /search-results                       |
| url                                            | queryParam                          | The query parameter appended to the SRLP URL                                                                                                                                  | q                                     |
| search                                         | apiKey                              | Klevu JS Api Key which will be used for search requests                                                                                                                       | <font color="#3b9f0f">REQUIRED</font> |
| search                                         | infiniteScrollOffset                | Determines the pixel distance from bottom of the quicksearch (faceted layout display) to trigger the next result dataset                                                      | 50                                    |
| search                                         | infiniteScrollOffsetLanding         | Determines the pixel distance from bottom of the webpage to trigger the next result dataset<br />Determines the pixel distance of the page to trigger the next result dataset | 50                                    |
| search                                         | searchBoxSelector                   | The id, class, or handle used to bind the search input field                                                                                                                  | <font color="#3b9f0f">REQUIRED</font> |
| search                                         | searchBoxTarget                     | Define a target for the results generation                                                                                                                                    | false                                 |
| search                                         | showQuickOnEnter                    | Disable the enter/return key in the quick search                                                                                                                              | false                                 |
| search                                         | sliderPriceDelimiter                | Set the delimiter between the currency symbol and the price for the price slider                                                                                              | " "                                   |
| search                                         | fullPageLayoutEnabled               | Avoid focusout event                                                                                                                                                          | false                                 |
| search                                         | minChars                            | Number of typed characters required                                                                                                                                           | 3                                     |
| search                                         | placeholder                         | Placeholder text of the search box                                                                                                                                            | ""                                    |
| search                                         | personalisation                     | Control of personalisation                                                                                                                                                    | false                                 |
| search                                         | redirects                           | Redirects for specific search term<br />"term": "https\://full-url.com". Enter terms as lowercase.                                                                            | \{}                                   |
| recs                                           | apiKey                              | Klevu JS Api Key used for Smart Recommendations                                                                                                                               |                                       |
| analytics                                      | apiKey                              | Klevu JS Api Key used for general analytics reporting                                                                                                                         | <font color="#3b9f0f">REQUIRED</font> |
| global                                         | apiKey                              | Klevu JS Api Key used for all components                                                                                                                                      | OPTIONAL                              |
| theme                                          | quicksearch:<br />loadDefaultStyles | Stop Klevu Quicksearch template styles from loading                                                                                                                           | true                                  |
| theme                                          | landing:<br />loadDefaultStyles     | Stop Klevu SRLP template styles from loading                                                                                                                                  | true                                  |
| theme                                          | catnav:<br />loadDefaultStyles      | Stop Klevu Category template styles from loading                                                                                                                              | true                                  |
| theme                                          | setTemplates                        | Specify one or more Klevu templates to override. Read [Set Template](docId:6YVX9naw6AX68WYguCOB7) for more information.                                                       |                                       |
| theme:<br />modules:<br />resultInfiniteScroll | quickSearch:<br />enable            | Set "true" to enable Infinite Scroll                                                                                                                                          |                                       |
| theme:<br />modules:<br />resultInfiniteScroll | searchResultsPage:<br />enable      | Set "true" to enable Infinite Scroll                                                                                                                                          |                                       |
| theme:<br />modules:<br />resultInfiniteScroll | categoryPage:<br />enable           | Set "true" to enable Infinite Scroll                                                                                                                                          |                                       |
| fetchSettings                                  | fallback                            | Set "true" to activate the fetch fallback to use fetch interface with url + headers. This is useful native fetch function has been replaced.                                  |                                       |
| dataProtection                                 | useConsent                          | Set "true" to activate data protection system. This defines if consent should be checked site-wide. This is an opt-in system.                                                 | false                                 |
| dataProtection                                 | consentState                        | The value of the consent state for the current user. This value should be set based on whether the user has given consent to send data to Klevu.                              | false                                 |

## Useful Configuration Setting Examples

The above configuration settings can be passed directly into the main klevu function as an object as shown below.&#x20;

### Code Example

```javascript
klevu({
  search: {
    minChars: 2,
    placeholder: "Ready to search?",
    redirects: {
      "my cool blue": "https://mywebsite.com/my-cool-blue-product",
      "hot": "https://mywebsite.com/sale"
    }
  }
});
```

## Useful Local Storage Settings

| Key Name                 | Key Value Default | Description                                                                                                   |
| ------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------- |
| klv\_limits\_productList | 12                | By default the Template JS library makes 12, 24, and 36 options available, but this can be set to any number. |
| klv\_limits\_contentList | 12                | By default the Template JS library makes 12, 24, and 36 options available, but this can be set to any number. |

### Code Example

```javascript
// This code waits for klevu.js to load first.
window._klvReady= window._klvReady|| [];
window._klvReady.push(function(){
  
  // We will set the items per page one time using a variable.
  var itemsPerPage = 24;
  
  // Now we can use the variable to set both the product and content tab
  // items per page.
  localStorage.setItem('klv_limits_productList', itemsPerPage);
  localStorage.setItem('klv_limits_contentList', itemsPerPage);
});
```

## Useful Data Protection Settings

Klevu's Template JS library uses an opt-in consent system that controls whether the library can or cannot send user activity data to Klevu. This does not stop Klevu services like Search and Recommendations from working, but rather it can block any user activity data from being sent to Kelvu. This data is what can power personalized user experiences and the main algorythm that powers all of Klevu.&#x20;

In other words, when you opt-in to using the consent system, each user can consent or not consent to sending this activity data. You can use any mechanism you would like to ask and track this consent, but you can use the following settings to tell the library that a user has given or not given consent.&#x20;

### Basic Code Example

```javascript
klevu({
  dataProtection: {
    useConsent: true, // enable the consent system for all users
    consentState: false, // user-specific setting to opt-in or out
  }
});
```

Because the consent system is opt-in, it is not required to use these settings. If you do want to use the consent system, then make sure useConsent is always set to "true". And for each user, set their consentState to "true" or "false".&#x20;

Most customer that use the consent system will set useConsent to "true" and consentState to "false" until the user has specifically given consent. Then you can set consentState to "true" for that user.&#x20;

### Robust Code Example

If you encouter any issues where you get errors or the consentState is not showing the value you are setting by using the Basic Code Example, try this version instead.

```javascript
window._klvReady = window._klvReady || [];
window._klvReady.push(function () {
  // Replace the return value with the site's own consent logic.
  function getConsentState() {
    return false; 
  }

  // initChain runs on every klevu() call before values are persisted,
  // so pinning them here makes the site's values win.
  klevu.settings.chains.initChain.addBefore('dataProtectionCheck', {
    name: 'siteConsentGuard',
    fire: function (data) {
      klevu.setObjectPath(data, 'dataProtection.useConsent', true);
      klevu.setObjectPath(data, 'dataProtection.consentState', getConsentState());
    }
  });

  // Necessary call to re-run the initChain.
  klevu({ dataProtection: {} });
});
```

This version wraps the dataProtection code in a function that waits for the KIevu library to be ready and also waits to send the dataProtection values after all other settings are applied to ensure they are applied properly.&#x20;

## Useful Session Storage Settings

For Key Names that include \[apiKey] you would replace this with your account's apiKey value. Here's an example:

```javascript
sessionStorage.setItem(`klv_view_klevu-14728819608184175_productList`, 'grid');
```

| Key Name                          | Key Value Default | Description                             |
| --------------------------------- | ----------------- | --------------------------------------- |
| klv\_view\_\[apiKey]\_productList | grid              | Available values are "grid" and "list". |
| klv\_view\_\[apiKey]\_contentList | list              | Available values are "grid" and "list". |

### Code Example

```javascript
// This code waits for klevu.js to load first.
window._klvReady= window._klvReady|| [];
window._klvReady.push(function(){

  // Run this function when Search and/or Category pages load.
  klevu.beforeActivation('landing,catnav', function(data ,scope){
    
    // Set session storage value using a useful function to dynamically 
    // retrieve your apiKey.
    sessionStorage.setItem(`klv_view_${klevu.pageMeta.getApiKey()}_productList`, 'list');
    
  }, 'build');
});
```




[title] SortBy Options
[path] How To/



The default SortBy functionality can be modified within Template JS by overriding the default Script block. Additional supported options can be added as well as edits to the default labeling.

See : [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu JS overriding

See : An in-action example and the source code on the [Klevu CodeSandbox](https://codesandbox.io/s/change-sorting-options-867krq)

## Indexing

:::hint{type="success"}
Supported options for product sorting must be supplied at the product level

- price / sale\_price
- title
- rating
- id / date\* (for newness)&#x20;
:::

\*Please see this [support article](https://help.klevu.com/support/solutions/articles/5000871480-sort-order-options) for important information about sorting by newness.



## API Reference

| **Parameter**                         | **Description**                                                                               |
| ------------------------------------- | --------------------------------------------------------------------------------------------- |
| RELEVANCE                             | Default combination of Klevu A.I. and merchandising configuration                             |
| PRICE\_ASC, PRICE\_DESC               | Sort the results by the `salePrice` value of each record                                      |
| NAME\_ASC, NAME\_DESC                 | Sort the results by the `name` of each record, in alphabetical order                          |
| RATING\_ASC, RATING\_DESC             | Sort the results by each record's average rating, if this data has been indexed in your store |
| NEW\_ARRIVAL\_ASC, NEW\_ARRIVAL\_DESC | Sort your records based on their published date.                                              |

See :  Klevu API Documentation for available [Sorting Options](https://docs.klevu.com/apis/smart-search-configurations)



## Template JS Override

The SortBy options template block can be modified using the [Set Template](docId:6YVX9naw6AX68WYguCOB7) override.  The [Set Custom Helpers](docId\:Q0fQR_0VzOsbxRbf7RS_L) are used to modify the desired display text of the selected option as well.

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">

klevu({
	theme: {
      setTemplates: {
		 myCustomSortBy: {
		  scope: "landing,catnav", 
		  selector: "#myCustom_klevuLandingTemplateSortBy",
		  name: "sortBy"
		 }
	  },
	  setHelpers: {
        "landing,catnav": {
            myCustomSortBy: function(dataLocal) {
              /* sets the selected option to the display */

              var selectedText = "";

              var klevuStorage = klevu.getSetting(klevu.settings, "settings.storage");

              switch (klevuStorage.sort.getElement(dataLocal) == dataLocal ? "RELEVANCE" : klevuStorage.sort.getElement(dataLocal)) {
                case "RELEVANCE":
                    selectedText = "Best Match";
                    break;
                case "PRICE_ASC":
                    selectedText = "Price: Low to high";
                    break;
                case "PRICE_DESC":
                    selectedText = "Price: High to low";
                    break;
                case "NAME_ASC":
                    selectedText = "Name: A to Z";
                    break;
                case "NAME_DESC":
                    selectedText = "Name: Z to A";
                    break;
                case "NEW_ARRIVAL_DESC":
                    selectedText = "Newest to Oldest";
                    break;
                case "NEW_ARRIVAL_ASC":
                    selectedText = "Oldest to Newest";
                    break;
                default:
                    selectedText = "Best Match";
              }
              return selectedText;
          }
        }
      }
	}
});
</script>


<script type="template/klevu" id="myCustom_klevuLandingTemplateSortBy">
  <div class="kuDropdown kuDropSortBy" role="listbox">
    <div class="kuDropdownLabel">
      <%=helper.translate("Sort by : ")%><%=helper.myCustomSortBy(dataLocal)%>
    </div>
    <div class="kuDropdownOptions">
      <div class="kuDropOption kuSort" data-value="RELEVANCE" role="option">Best Match</div>
      <div class="kuDropOption kuSort" data-value="PRICE_ASC" role="option">Price: Low to high</div>
      <div class="kuDropOption kuSort" data-value="PRICE_DESC" role="option">Price: High to low</div>
      <div class="kuDropOption kuSort" data-value="NAME_ASC" role="option">Name: A to Z</div>
      <div class="kuDropOption kuSort" data-value="NAME_DESC" role="option">Name: Z to A</div>
      <div class="kuDropOption kuSort" data-value="NEW_ARRIVAL_DESC" role="option">Newest to Oldest</div>
      <div class="kuDropOption kuSort" data-value="NEW_ARRIVAL_ASC" role="option">Oldest to Newest</div>
  </div>
 </div>
</script>


```
:::


[title] Items Per Page
[path] How To/



The Klevu Template JS Search and Category result display has a built in default product per-page limit of 12.&#x20;

The default selectable **Items Per Page** product limit options are divisible by 12.

- 12
- 24
- 36

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/_cMS18Y0I_GcI7fbuQyUE_screen-shot-2023-06-22-at-22131-pm.png" size="54" width="578" height="398" caption="Default Options" position="center" showCaption="true"}

When a visitor selects the desired item count value from the Template JS dropdown, the value is stored in the browser's Local Storage corresponding to the *query-type/id*.

| **Local Storage Key**      | **Description**               |
| -------------------------- | ----------------------------- |
| klv\_limits\_*productList* | The main product result array |
| klv\_limits\_*contentList* | The CMS content result array  |



## Setting Defaults

The default count can be set directly into the Local Storage using parameter for `klv_limits_[REQUEST ID]`.

**For example:** Setting the default count to **36** for each query type can be accomplished using the following method

:::BlockQuote
&#x20;/\* set default product limits \*/
&#x20; window.\_klvReady= window.\_klvReady|| \[];
&#x20; window.\_klvReady.push(function()\{
&#x20;    var itemsPerPage = **36**;
&#x20;    localStorage.setItem('klv\_limits\_productList', itemsPerPage);
&#x20;    localStorage.setItem('klv\_limits\_contentList', itemsPerPage);
&#x20; });
:::

If you are using Infinite Scroll or Load More, the settings above will not be applied and you must modify the search request to Klevu in order to change the limit.&#x20;

We used 15 as an example, but change your limit as needed. This limit controls the items per page to display.

```javascript
window._klvReady = window._klvReady || [];
window._klvReady.push(function(){
	klevu.beforeActivation('landing,catnav', function(data, scope){
        klevu.each(data.request.current.recordQueries, function (key, query) {
            const queryID = klevu.getObjectPath(query, "id");
            if (queryID === "productList" || queryID === "contentList") {
                // change this to your desired limit
                klevu.setObjectPath(query, "settings.limit", 15);
            }
        });	
	});
});
```

## Changing Selectable Options

To change the selectable options within the Klevu Template UI, the block for `klevuLandingTempalteLimit > limit` will need to be overridden to include the new values.&#x20;

**For example :** The below snippet uses a Custom [Set Template](docId:6YVX9naw6AX68WYguCOB7) override to modify the selectable limits available in the interface as 5/10/15 with a default value of 5

```javascript
 <script type="text/javascript">
      /* Assign new templates to Klevu Options */
      klevu({
        theme: {
          setTemplates: {
            myCustomLimit: {
              scope: "full_page", // impacted scope
              selector: "#myCustom_klevuLandingTemplateLimit", // new markup block ID
              name: "limit" // template placement name
            }
          }
        }
      });
      
       /* set default product limits */
        window._klvReady= window._klvReady|| [];
        window._klvReady.push(function(){
           var itemsPerPage = 5;
           localStorage.setItem('klv_limits_productList', itemsPerPage);
           localStorage.setItem('klv_limits_contentList', itemsPerPage);
        });
      
</script>
     
<!-- new limit selection template --> 
<script type="template/klevu" id="myCustom_klevuLandingTemplateLimit">
       <div class="kuDropdown kuDropItemsPerpage">
          <div class="kuDropdownLabel"><%=helper.translate("Items per page : %s",helper.getLimit(dataLocal))%></div>
          <div class="kuDropdownOptions">
              <div class="kuDropOption kuLimit" data-value="5">5</div>
              <div class="kuDropOption kuLimit" data-value="10">10</div>
              <div class="kuDropOption kuLimit" data-value="15">15</div>
          </div>
      </div>
</script>
```


[title] Quickstart : Smart Search
[path] Getting Started/



There are three primary aspects required for any implementation

- Core reference files
- settings/configuration
- page elements / markup

The required reference files and corresponding markup may vary depending on the page context.&#x20;

:::hint{type="info"}
**Note:**  the Klevu configurations should be set globally.
:::

See : [Structure](docId\:pUmT_E7JdsEaf0Pa2FM8F) section for more detail on these components.

## Quick Search

The following code is the minimum required to get a quick search, or auto-suggestions overlay, to appear.&#x20;

This code sample contains:

- JS Library core reference -  klevu.js
- Quick Search Theme Layout reference - quick-search.js&#x20;
- Configuration JavaScript -  options variable
- Searchbox HTML target - \<input>&#x20;

These elements are generally placed on a global template for use throughout the entire website.

Copy (or adapt) this to a webpage and as soon as you click on the search box you should see some results appearing.

```html
<!DOCTYPE html>
<html>
<head>
<!-- Include JS Library -->
<script src="https://js.klevu.com/core/v2/klevu.js"></script>

<!-- Include Quick Search Theme -->
<script src="https://js.klevu.com/theme/default/v2/quick-search.js"></script>

    <!-- Configure Klevu for your store -->
    <script type="text/javascript">
       var options = {
         url : {
            landing : '/search-results',
                protocol: 'https:',
                search: 'https://eucs3v2.ksearchnet.com/cs/v2/search' // your Klevu APIv2 Search URL + endpoint path
            },
            search: {
                minChars: 0,
                searchBoxSelector: "#my-search", // your search input selector
                apiKey: "klevu-14728819608184175" // your Klevu JS API Key
            },
            analytics: {
                apiKey: 'klevu-14728819608184175' // your Klevu JS API Key
            }
        };
        klevu(options);
    </script>
</head>
<body>
<!-- The ID of the input matches 'searchBoxSelector' above -->
<form action="#">
    <input id="my-search" name="q" type="text">
</form>
</body>
</html>
```



## Search Results Landing Page

The snippet above will direct the search to the relative URL **/search-results** as indicated using value assigned to `options.url.landing `

The following Search Results Landing Page code sample will build on the previous by including 2 additional elements:

- SRLP Theme Layout reference - search-results-page.js&#x20;
- Search Result HTML target/placeholder - \<div>

The following code is for the  `/search-results` webpage that now contains all the required elements.

```html
<!DOCTYPE html>
<html>
<head>
<!-- Include JS Library -->
<script src="https://js.klevu.com/core/v2/klevu.js"></script>

<!-- Include Quick Search Theme -->
<script src="https://js.klevu.com/theme/default/v2/quick-search.js"></script>

<!-- Include Search Results Theme -->
<script src="https://js.klevu.com/theme/default/v2/search-results-page.js"></script>

    <!-- Configure Klevu for your store -->
    <script type="text/javascript">
      var options = {
          url : {
              landing : '/search-results',
              protocol: 'https:',
              search: 'https://eucs3v2.ksearchnet.com/cs/v2/search' // your Klevu APIv2 Search URL + endpoint path
          },
          search: {
              minChars: 0,
              searchBoxSelector: "#my-search", // your search input selector
              apiKey: "klevu-14728819608184175" // your Klevu JS API Key
          },
          analytics: {
              apiKey: 'klevu-14728819608184175' // your Klevu JS API Key
          }
      };
      klevu(options);
  </script>
</head>
<body>
<!-- The ID of the input matches 'searchBoxSelector' above -->
<form action="#">
    <input id="my-search" name="q" type="text">
</form>
    <!-- Add a placeholder where the search results will be injected -->
    <div class="klevuLanding"></div>
</body>
</html>
```



:::hint{type="info"}
**Note:** The index credentials used in this guide are specific for the Klevu Demo Store catalog.&#x20;

You are welcome to use the demo catalog for experiments and learning. Please adapt to your specific catalog as soon as possible to benefit from any specific modifications you will need for the success of your implementation.


:::

## Using Your Own Data

There are some small modifications you will need to make to the Klevu configuration within the options JavaScript variable in our examples in order for use with your Klevu Index and/or your specific integration.&#x20;

| **Element**           | **Configuration Options**  | **Description**                                                                                                                                                                                                                                                  |
| --------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Landing Page Path     | `url.landing`              | The url path to send customers to access the full search results                                                                                                                                                                                                 |
| Search Box Selector   | `search.searchBoxSelector` | The class or ID or handle used to locate the input search box(es)                                                                                                                                                                                                |
| Search Query Paramter | `url.queryParam`           | The `name` of the search `<input>` to be used as the query parameter in the SRLP URL                                                                                                                                                                             |
| Search URL            | `url.search`               | Your Klevu [Cloud Search URL ](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)+ endpoint path |
| Search API Key        | `search.apiKey`            | Your Public Klevu [JS API Key](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)                |
| Analytics API Key     | `analytics.apiKey`         | Your Klevu [Analytics API Key](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)                |

:::hint{type="info"}
You can find your specific API Key and Endpoint information from <font color="#eb144c"> </font>within your Klevu Merchant Center
:::

See: [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu)  for more details.

[title] Quickstart : Smart Category Merchandising
[path] Getting Started/



There are three primary aspects required for any implementation

- Core reference files
- settings/configuration
- page elements / markup

The required reference files and corresponding markup may vary depending on the page context.&#x20;

:::hint{type="info"}
**Note:**  the `klevu.interactive` configurations should be set globally.
:::

See : [Structure](docId\:pUmT_E7JdsEaf0Pa2FM8F) section for more detail on these components.

## Category Pages

The following code is the minimum required to get a Category Page up and running.&#x20;

**Note:&#x20;**&#x54;he sample below does not contain any additional Klevu functions (Quick Search and Search Result Landing Page). For details on those aspects please review the [Quickstart : Smart Search](docId\:AMGa2LZ3adsU1tVJxhg1K)&#x20;

This code sample contains:

- JS Library core reference -  klevu.js
- Configuration JavaScript -  klevu.interactive
- Category Page Theme Layout reference - category-page.js&#x20;
- Search Result HTML target/placeholder - \<div>



```html
<!DOCTYPE html>
<html>
<head>
    <!-- Include JS Library -->
    <script src="https://js.klevu.com/core/v2/klevu.js"></script>

    <!-- Include Category Page Theme -->
    <script src="https://js.klevu.com/theme/default/v2/category-page.js"></script>

    <!-- Configure Klevu for your store -->
    <script type="text/javascript">
        klevu.interactive(function () {
            var options = {
                url : {
                    protocol: 'https:',
                    search: 'https://eucs3v2.ksearchnet.com/cs/v2/search' // your Klevu APIv2 Search URL + endpoint path
                },
                search: {
                    apiKey: "klevu-14728819608184175" // your Klevu JS API Key
                },
                analytics: {
                    apiKey: 'klevu-14728819608184175' // your Klevu JS API Key
                }
            };
            klevu(options);
        });
    </script>

    <!-- Provide current category context -->
    <script type="text/javascript">
        var klevu_pageCategory = "Clothing";
        sessionStorage.setItem("klevu_pageCategory", klevu_pageCategory);
    </script>
</head>
<body>
    <!-- Add a placeholder where the results will be injected -->
    <div class="klevuLanding"></div>
</body>
</html>
```



:::hint{type="info"}
**Note**: The index credentials used in this guide are specific for the Klevu Demo Store catalog.&#x20;

You are welcome to use the demo catalog for experiments and learning. Please adapt to your specific catalog as soon as possible to benefit from any specific modifications you will need for the success of your implementation.


:::

## Using Your Own Data

There are some small modifications you will need to make to the above code in order for use with your Klevu index.&#x20;

| **Element**        | **JavaScript Varliable** | **Description**                                                                                             |
| ------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------- |
| Category Page Name | `var klevu_pageCategory` | The page specific Category name. <br />**This value must match the category value defined during indexing** |

| **Element**       | **klevu.interactive Options** | **Description**                                                                                                                                                                                                                                                   |
| ----------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Search URL        | `url.search`                  | Your Klevu [Cloud Search URL ](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-) + endpoint path |
| Search API Key    | `search.apiKey`               | Your Public Klevu [JS API Key](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)                 |
| Analytics API Key | `analytics.apiKey`            | Your Klevu [Analytics API Key](https://help.klevu.com/support/solutions/articles/5000876417-how-to-retrieve-store-specific-api-keys--js-template-version-and-end-points-for-product-sync--querying-indexed-data-and-submitting-analytics-events-)                 |

:::hint{type="info"}
You can find your specific API Key and Endpoint information from <font color="#eb144c"> </font>within your Klevu Merchant Center
:::

See: [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu)  for more details.

[title] Shopify
[path] Getting Started/Apps/Plug-ins/



There are two options for implementing the Klevu Template JS on Shopify:

1. Automated via the Klevu Shopify App (available from the Shopify Marketplace)
2. Manual implementation of the files into the Shopify Theme

Manual install may be required for the following conditions:

- Your Shopify Theme has been modified or is otherwise preventing the Klevu App automation
- You are installing Klevu on a an unpublished theme

## Marketplace App (App Embeds & Blocks)

:::hint{type="warning"}
**Since Jan 9th, 2024,** the Klevu application is no longer able to directly make changes to your theme code, as per Shopify’s guidelines. Instead, this extension utilizes App Embeds and Blocks within the Shopify Theme Editor, giving you more control over the look and feel of Klevu solutions without having to write any code.
:::

Please review the instructions in the Klevu Knowledgebase for [Integrating Klevu Solutions in Shopify](https://help.klevu.com/support/solutions/articles/5000886912-integrating-klevu-solutions)



## Marketplace App&#x20;

:::hint{type="warning"}
If you integrated your storefront with **Klevu before Jan 9th, 2024**, all solutions will continue to work as currently without any action required from you, however you will need to either continue managing theme modifications manually or contact our support team to explore if you can move to the App Embeds & Blocks approach.
:::

You can find detailed installation steps on the Klevu Knowledgebase article[ Integration Steps For Shopify](https://help.klevu.com/support/solutions/articles/5000871264-integration-steps-for-shopify)

Once installed, the template JS resources will be available as placed automatically by the [Klevu Shopify App](https://apps.shopify.com/klevu-smart-search).

The following is a summary of automated steps as part of the Klevu Shopify App installation:&#x20;

1. Placement of liquid reference files
   - snippets/klevu-quick-search-theme  (core reference, config/options)
   - snippets/klevu-add-to-cart (button functionality)
   - snippets/klevu-catnav-theme (collection core  - if applicable)
   - snippets/klevu-recommendations (recommendations core - if applicable)
   - snippets/klevu-metadata (recommendations support - if applicable)
   - sections/klevu-collection-theme (collection landing page - if applicable)
   - templates/page.klevu-search-results (search landing page template)
2. Adds core includes of the above files to ***layout/theme.liquid***
3. Adds settings object or target (Depending on Shopify version)
   - 2.0 (Dawn) :  ***templates/collection.json&#x20;***
   - 1.0 (Debut) :  ***templates/collection.liquid&#x20;***
4. Authorizes Shopify API for hourly Catalog Synchronization



## Manual Installation

If your Shopify Theme has been modified or is otherwise preventing the above automated installation, you can manually install Klevu Template JS using the strategies outlined below, or a variation of it that fits your architecture.

We recommend implementing these steps on an **unpublished theme** to avoid any unforeseen conflicts with the live site.

The [Klevu Shopify App](https://apps.shopify.com/klevu-smart-search) will still need to be installed to facilitate the catalog indexing. However, on Step 9 of the Klevu Knowledgebase article[ Integration Steps For Shopify](https://help.klevu.com/support/solutions/articles/5000871264-integration-steps-for-shopify)﻿ , leave the "Klevu Solutions" marked as "**disabled**".

The steps as outlined in the [Quickstart : Smart Search](docId\:AMGa2LZ3adsU1tVJxhg1K) can be applied as you like into the Shopify theme files.

Alternatively, please reference[ the complete technical walkthrough](https://support.klevu.com/hc/en-us/articles/39396919314843-Theme-Modifications-for-JSv2-OS2-Dawn) if you would like to mirror the Klevu App's default installation procedure.

Klevu Smart Recommendations integration options are covered in the Knowledgebase guide: [Smart Recommendations Integration Guide for Shopify](https://help.klevu.com/support/solutions/articles/5000871327-integration-steps-for-shopify)

[title] Quickstart : Smart Recommendations
[path] Getting Started/

## App/Plugin Integration

If you are integrating Smart Recommendations on a platform using one of the supported apps or extensions, please consult the applicable Knowledgebase article for specific instructions on implementation.

- Shopify - [Integration Guide](https://help.klevu.com/support/solutions/articles/5000871327-integration-steps-for-shopify)
- Magento - [Integration Guide](https://help.klevu.com/support/solutions/articles/5000871321-integration-steps-for-magento2)
- BigCommerce - [Integration Guide](https://help.klevu.com/support/solutions/articles/5000871324-integration-steps-for-bigcommerce)



## Basic Integration

Below we have highlighted the generic skeleton which will work on any platform. Please ensure these elements are included within the **\<head/>** of every page of your website where you wish to show Klevu Recommendation banners.

Please refer to the [Recommendations Getting Started guide](https://help.klevu.com/support/solutions/articles/5000871315-getting-started) for other aspects like creating a banner and adding it to your store, editing a banner, etc. 

:::hint{type="info"}
Any customers already using Klevu JavaScript Library (aka JSv2) may already have the `klevu.js` library included
:::

```html
<html>
<head>
        <script type="text/javascript">
        // use your own logic to determine the current page type
        var page_type = 'REPLACE ME!';

        if (page_type == 'category') {
            var klevu_page_meta = {
                'pageType': "category",

                // If your catalogue supports category hierarchy, please provide the full path of category names separated by semi-colon. For example Mens > Shoes > Sneakers would be Mens;Shoes;Sneakers
                'categoryName': 'REPLACE ME!',

                // The full URL to the category. For example https://your.store.com/mens/shoes/sneakers
                'categoryUrl': 'REPLACE ME!'
            };
        }
        if (page_type == 'product') {
            var klevu_page_meta  = {
                "pageType": "pdp",

                // The name of the current product
                "itemName": "REPLACE ME!",

                // The full URL to the product. For example https://your.store.com/mens/shoes/sneakers
                "itemUrl": "REPLACE ME!",

                // The ID you specify here must match the one provided to Klevu as <id/>
                "itemId": "REPLACE ME!",

                // The ID you specify here must match the one provided to Klevu as <item_group_id/>
                "itemGroupId": "REPLACE ME!",

                // The final selling price of the product, eg. 123.45
                "itemSalePrice": "REPLACE ME!",

                // The currency code of the above price, eg. USD
                "itemCurrency": "REPLACE ME!"
            };
        }
        if (page_type == 'cart') {
            var cartRecords = [];

            // Repeat this block for each item the customer has in their cart
            cartRecords.push({'itemId': 'REPLACE ME!' ,'itemGroupId': 'REPLACE ME!'});

            var klevu_page_meta = {
                'pageType': "cart",
                'cartRecords': cartRecords
            };
        }
    </script>
    <script src="https://js.klevu.com/core/v2/klevu.js"></script>
    <script src="https://js.klevu.com/recs/v2/klevu-recs.js"></script>
    <script type="text/javascript">
        klevu.interactive(function () {
            var options = {
                powerUp: {
                    recsModule: true
                },
                recs: {
                    apiKey: 'klevu-12345'
                }
            };
            klevu(options);
        });

    </script>
</head>
<body>
    <div class="klevu-recs" id="ABC-123"></div>
</body>
</html>
```



## Recommendation Templates

Recommendations templates are managed within the store Klevu Merchant Center

Please refer to the [Recommendations Getting Started guide](https://help.klevu.com/support/solutions/articles/5000871315-getting-started) for aspects like creating a banner and adding it to your store, editing a banner, etc. 

[title] Magento
[path] Getting Started/Apps/Plug-ins/

## Klevu Magento Module v4&#x20;

Rebuilt from the ground up, around Klevu's JSON indexing APIs, with a focus on Magento best practices and ease of customization.

- **Adobe Commerce**: `2.4.4` - `2.4.7-p2`.
- **Magento Open Source**: `2.4.4` - `2.4.7-p2`.
- **PHP**: `8.1` - `8.3`.
- **Hyvä Themes.**

For the complete integration guide please see the [Klevu Module v4.x Overview](docId\:hrAN4Or8yipiwynmOcM3c) documentation.

:::hint{type="warning"}
For older versions of Magento, please refer to the Klevu module integration guide for versions 2.x/3.x available [here](https://help.klevu.com/support/solutions/articles/5000871252-integration-steps-for-magento-2).&#x20;
:::



## Enabling Template JS

Enabling or disabling Quick Search, Search Results Landing Page, Category Navigation and Recommendations are all handled in the same configuration area.

**Klevu V4 :**  Navigate to `Stores > Configuration > Klevu > Frontend`

**Klevu V2/V3 :** Navigate to `Magento Admin > Stores > Configuration > Klevu Search > Developer Settings` 

To enable Template JS:

- Change this value to Klevu Theme (or JSv2) as required for the current store.
- Select Klevu JS Theme for Search (and Category pages if applicable).
- Flush the Magento cache.

The Klevu Template JS will now be active for the store.

For more details on Klevu V4 Frontend implementation, please see the V4 [Theme JS Overview](docId:3WwCazakz4lwhww6nK7IS) documentation.



## Customizations

There are a number of ways to implement the Klevu Template customization overrides depending on your current Magento Theme structure and preferences.

Please see the [Set Template](docId:6YVX9naw6AX68WYguCOB7) documentation for details on preparing for Klevu JS overriding.

:::hint{type="danger"}
Never make changes to the Klevu extension files directly as this will break the upgrade path when updates are released.
:::



## Magento 1

Please see our Knolwedgebase article for [integration with Magento V1](https://help.klevu.com/support/solutions/articles/5000871277-integration-steps-for-magento-1)

[title] Template Reference
[path] Build UI/Templates Customizations/

The template `id` is assigned to the template `name` during the rendering process.

Use the charts below to quickly reference the default template associations

:::hint{type="info"}
**Note:** When viewing the reference URL in the browser, use **view-source** to see the templates default markup
:::

## QuickSearch

:::BlockQuote
[https://js.klevu.com/theme/default/v2/quick-templates.tpl](https://js.klevu.com/theme/default/v2/quick-templates.tpl)
:::

| **Script Template ID**                  | **Render Name**                       |
| --------------------------------------- | ------------------------------------- |
| #klevuQuickTemplateBase                 | klevuTemplateBase                     |
| #klevuQuickProducts                     | klevuQuickProducts                    |
| #klevuQuickProductBlock                 | klevuQuickProductBlock                |
| #klevuQuickNoResultFound                | klevuQuickNoResultFound               |
| #klevuSearchPersonalizations            | klevuSearchPersonalizations           |
| #klevuQuickTemplateResultsHeadingTitle  | klevuQuickTemplateResultsHeadingTitle |
| #klevuQuickProductBlockTitleHeader      | klevuQuickProductBlockTitleHeader     |
| #klevuQuickAutoSuggestions              | klevuQuickAutoSuggestions             |
| #klevuQuickPageSuggestions              | klevuQuickPageSuggestions             |
| #klevuQuickCategorySuggestions          | klevuQuickCategorySuggestions         |
| #klevuQuickTemplatePagination           | klevuQuickTemplatePagination          |
| #klevuQuickPromotionBanner              | klevuQuickPromotionBanner             |
| #kuTemplatePopularSearches              | kuTemplatePopularSearches             |
| #kuTemplateRecentSearches               | kuTemplateRecentSearches              |
| #klevuQuickTrendingProductBlock         | klevuQuickTrendingProductBlock        |
| #klevuTrendingProducts                  | klevuTrendingProducts                 |
| #klevuQuickRecentViewedProductBlock     | klevuQuickRecentViewedProductBlock    |
| #klevuRecentViewedProducts              | klevuRecentViewedProducts             |
| #klevuTemplateNoResultFoundQuick        | noResultsFoundQuick                   |
| #klevuQuickNoResultsFoundBanners        | quickNoResultsFoundBanners            |
| #kuQuickNoResultsPopularSearches        | quickNoResultsPopularSearches         |
| #klevuQuickNoResultsPopularProducts     | quickNoResultsPopularProducts         |
| #klevuQuickNoResultsPopularProductBlock | quickNoResultsPopularProductBlock     |
| #quickSearchResultProductStock          | quickProductStock                     |
| #searchResultProductVATLabelQuick       | searchResultProductVATLabelQuick      |
| #klevuQuickTemplateFilters              | klevuQuickTemplateFilters             |
| #klevuQuickTemplateSortBy               | klevuQuickTemplateSortBy              |
| #kuTemplateQuickResultsViewSwitch       | kuTemplateQuickResultsViewSwitch      |
| #klevuQuickTemplateTabResults           | klevuQuickTemplateTabResults          |
| #klevuQuickOtherContent                 | klevuQuickOtherContent                |
| #klevuQuickTemplateContentBlock         | klevuQuickTemplateContentBlock        |
| #klevuQuickImageSearchContent           | klevuQuickImageSearchContent          |
| #klevuQuickProductRating                | klevuQuickProductRating               |



## Search Result Page

:::BlockQuote
[https://js.klevu.com/theme/default/v2/landing-templates.tpl](https://js.klevu.com/theme/default/v2/landing-templates.tpl)
:::

| **Script Template ID**                   | **Render Name**                         |
| ---------------------------------------- | --------------------------------------- |
| #klevuLandingTemplateBase                | klevuTemplateLanding                    |
| #klevuLandingTemplateResults             | results                                 |
| #klevuLandingTemplateProductBlock        | productBlock                            |
| #klevuLandingTemplateResultsHeadingTitle | klevuLandingTemplateResultsHeadingTitle |
| #klevuLandingTemplatePagination          | pagination                              |
| #klevuLandingTemplateFilters             | filters                                 |
| #klevuLandingTemplateTopFilters          | filtersTop                              |
| #landingPageProductAddToCart             | landingPageProductAddToCart             |
| #landingPageProductColorSwatches         | landingProductSwatch                    |
| #quickViewProductColorSwatches           | quickViewProductSwatch                  |
| #landingSearchResultProductStock         | landingProductStock                     |
| #searchResultProductVATLabel             | searchResultProductVATLabel             |
| #klevuLandingTemplateSortBy              | sortBy                                  |
| #klevuLandingTemplateLimit               | limit                                   |
| #klevuLandingTemplateTabResults          | tab-results                             |
| #klevuLandingTemplateContentBlock        | contentBlock                            |
| #searchResultProductBadge                | landingProductBadge                     |
| #klevuLandingPromotionBanner             | klevuLandingPromotionBanner             |
| #klevuLandingTemplateNoResultFound       | noResultsFoundLanding                   |
| #klevuLandingNoResultsFoundBanners       | landingNoResultsFoundBanners            |
| #kuNoResultsPopularSearchesLanding       | noResultsLandingPopularSearches         |
| #klevuNoResultsPopularProductsLanding    | noResultsLandingPopularProductsTemplate |
| #kuFilterTagsTemplate                    | kuFilterTagsTemplate                    |
| #kuTemplateLandingResultsViewSwitch      | kuTemplateLandingResultsViewSwitch      |
| #klevuLandingTemplateSearchBar           | klevuLandingTemplateSearchBar           |
| #klevuQuickImageSearchContent            | klevuQuickImageSearchContent            |
| #landingImageRollover                    | landingImageRollover                    |
| #klevuLandingTemplateInfiniteScrollDown  | klevuLandingTemplateInfiniteScrollDown  |
| #klevuLandingImageSearchUploadBanner     | klevuLandingImageSearchUploadBanner     |
| #klevuLandingImageSearchUploadBanner     | klevuLandingImageSearchUploadBanner     |
| #klevuLandingProductRating               | klevuLandingProductRating               |
| #klevuLandingProductRatingCount          | klevuLandingProductRatingCount          |



## Category Page

:::BlockQuote
[https://js.klevu.com/theme/default/v2/catnav-templates.tpl](https://js.klevu.com/theme/default/v2/catnav-templates.tpl)
:::

| **Script Template ID**                   | **Render Name**                         |
| ---------------------------------------- | --------------------------------------- |
| #klevuLandingTemplateBase                | klevuTemplateLanding                    |
| #klevuLandingTemplateResults             | results                                 |
| #klevuLandingTemplateProductBlock        | productBlock                            |
| #klevuLandingTemplateResultsHeadingTitle | klevuLandingTemplateResultsHeadingTitle |
| #klevuLandingTemplatePagination          | pagination                              |
| #klevuLandingTemplateFilters             | filters                                 |
| #klevuLandingTemplateTopFilters          | filtersTop                              |
| #landingPageProductAddToCart             | landingPageProductAddToCart             |
| #landingPageProductAddToCart             | landingPageProductAddToCart             |
| #landingPageProductColorSwatches         | landingProductSwatch                    |
| #quickViewProductColorSwatches           | quickViewProductSwatch                  |
| #landingSearchResultProductStock         | landingProductStock                     |
| #searchResultProductVATLabel             | searchResultProductVATLabel             |
| #klevuLandingTemplateSortBy              | sortBy                                  |
| #klevuLandingTemplateLimit               | limit                                   |
| #searchResultProductBadge                | landingProductBadge                     |
| #klevuLandingPromotionBanner             | klevuLandingPromotionBanner             |
| #klevuLandingTemplateNoResultFound       | noResultsFoundLanding                   |
| #klevuLandingNoResultsFoundBanners       | landingNoResultsFoundBanners            |
| #kuNoResultsPopularSearchesLanding       | noResultsLandingPopularSearches         |
| #klevuNoResultsPopularProductsLanding    | noResultsLandingPopularProductsTemplate |
| #kuFilterTagsTemplate                    | kuFilterTagsTemplate                    |
| #kuTemplateLandingResultsViewSwitch      | kuTemplateLandingResultsViewSwitch      |
| #klevuLandingTemplateSearchBar           | klevuLandingTemplateSearchBar           |
| #klevuQuickImageSearchContent            | klevuQuickImageSearchContent            |
| #landingImageRollover                    | landingImageRollover                    |
| #klevuLandingTemplateInfiniteScrollDown  | klevuLandingTemplateInfiniteScrollDown  |
| #klevuLandingProductRating               | klevuLandingProductRating               |
| #klevuLandingProductRatingCount          | klevuLandingProductRatingCount          |



## Enable Template Hints

There are two steps to enable Template Hints:

- set a sessionStorage variable by opening your browser's Developer Tools, going to the Console and typing the following command:
  - `sessionStorage.setItem('klv_debugMode', true);`
- Once you have ran the above command in the Console you can append the parameter `klib_global_templateHints=true` to your URL.

:::BlockQuote
https\://www\.yourdomain.com/search/q=\***\&klib\_global\_templateHints=true**
:::

This will expose the micro-template positioning, each with a red border for context as well as the associated `name` used for rendering.

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/C0smdmanTnhmmlTzxWQ0O_image.png" size="54" width="565" height="547" caption="klib_global_templateHints=true" position="center" showCaption="true"}


[title] After Template Render
[path] Build UI/Templates Customizations/



There may be a use-case or business requirement in which a modification or action is needed to take place upon the rendering of the Klevu Template JS.

The `afterTemplateRender` function is triggered immediately after the last template has processed.

:::BlockQuote
**klevu.afterTemplateRender**("\<scope>", "\<callback>");
:::



## Identify the Data Object

The simplest way to get acquainted with the available data is to use **console.log** and review the output.

:::BlockQuote
klevu.afterTemplateRender("landing", function(data, scope)\{
&#x20;     **console.log('klevu.afterTemplateRender', data);**
&#x20;});
:::

For example, the following snippet loops through **each record in the productList result** and outputs the `product` object to the browser's developer **console.log**

:::BlockQuote
klevu.afterTemplateRender("all", function(data, scope)\{
&#x20; klevu.each(**data.template.query.productList.result**, function(indx, product)
&#x20; \{
&#x20;   **console.log('Klevu Template Product:' + indx, product);**
&#x20; });
});
:::



## Determining Scope

**Note** that each `klevu.afterTemplateRender` function requires definition within the corresponding `scope` of the override. We will chart these below.

| Scope      | Description                                               |
| ---------- | --------------------------------------------------------- |
| all        | Applies to all scope modules                              |
| quick      | QuickSearch module                                        |
| landing    | SRLP module                                               |
| catnav     | Category module                                           |
| full\_page | Both SRLP and Category modules (same as "landing,catnav") |

:::hint{type="success"}
Multiple `klevu.afterTemplateRender` functions can be applied in the same or mixed scope.
:::



## Example

The following snippet loops through **each record in the productList result** for the search *landing* page scope and adds an "ON SALE" notice using the DOM if there is a pricing discount applied.

```javascript
<script type="text/javascript">

klevu.afterTemplateRender("landing", function(data, scope){
  klevu.each(data.template.query.productList.result, function(indx, product)
  {
    if (product.price < product.salePrice) {
     var domElement = document.querySelector('li[data-id="'+product.id+'"] .kuProdBottom');
     domElement.innerHTML += '<strong style="color:red;">ON SALE</strong>';
     } 
  });
});

 </script>
```



::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/a1Mj01CJlinKDM-LHXfLb_image.png" size="40" width="300" height="325" caption="Example" position="center" showCaption="true"}


[title] Analytics/Tracking
[path] Build UI/Templates Customizations/

Klevu Template JS already includes the majority of analytics requirements out-of-the-box.&#x20;

If you are modifying the templates in any way, it is still important to understand the contents of this page, and validate your integration against the requirements below.

It is one of the key drivers behind Klevu Machine Learning; tracking customer searches and clicks to feed into our AI for relevant search results based on real customer interactions.

:::hint{type="info"}
Analytics collection is **required** for all integrations and should not be considered an optional element
:::



This page covers the minimum requirements for Klevu analytics. You may also decide that other interactions such as product views or interactions elsewhere in your website constitute a ‘click’, so you could also submit those if you choose.



:::hint{type="danger"}
Template JS Analytics event listeners are not responsible for order/checkout/purchase data. This call must be implemented during your platform checkout processing. See Purchases/*Orders Placed* section below
:::





# Analytics Events

If you elect to not use Klevu's built-in analytics collection events, the sections below can assist in setting up a system that fits your architecture the best

The following is a list of tracking events that are required in any Klevu implementation:

- Searched terms.
- Products clicked.
- Orders placed.

These events must be tracked in all areas of your store which contain a Klevu implementation, including:

- Quick Search.
- Search Results Landing Page.
- Category Pages using Klevu Smart Category Navigation.
- Landing Pages built with Klevu Landing Page Builder.

## Searched Terms

When the customer enters a search query, either via quick search or when reaching your search results landing page, it is important to inform Klevu of this activity.&#x20;

This is detailed in the [Klevu API Documentation](https://docs.klevu.com/apis/smart-search-analytics-events) and looks like this:

:::BlockQuote
https\://stats.ksearchnet.com/analytics/n-search/search
&#x20;    ?apiKey=klevu-1234567890
&#x20;    \&term=red%20shoes
&#x20;    \&klevu\_totalResults=35
&#x20;    \&klevu\_typeOfQuery=WILDCARD\_AND
:::



## Products Clicked (Search)

Once a customer has used quick search, viewed a search results page or landed on a klevu powered landing page, it is important to capture any product interactions they go on to make.&#x20;

This is detailed in the [Klevu API Documentation](https://docs.klevu.com/apis/smart-search-analytics-events) and looks like this:

:::BlockQuote
https\://stats.ksearchnet.com/analytics/productTracking
&#x20;    ?klevu\_apiKey=klevu-1234567890
&#x20;    \&klevu\_keywords=red%20shoe
&#x20;    \&klevu\_type=clicked
&#x20;    \&klevu\_productId=54321-12345
&#x20;    \&klevu\_productName=Smart%20Trainers
&#x20;    \&klevu\_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url
:::



## Products Clicked (Category)

Once a customer has viewed a category page powered by Klevu Smart Category Navigation, it is important to capture any product interactions they go on to make.&#x20;

This is detailed in the [Klevu API Documentation](https://docs.klevu.com/apis/smart-search-analytics-events) and looks like this:

:::BlockQuote
https\://stats.ksearchnet.com/analytics/categoryProductClickTracking
&#x20;    ?klevu\_apiKey=klevu-1234567890
&#x20;    \&klevu\_categoryName=Sneakers
&#x20;    \&klevu\_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers
&#x20;    \&klevu\_productId=54321-12345
&#x20;    \&klevu\_productName=Smart%20Trainers
&#x20;    \&klevu\_productUrl=https%3A%2F%2Fyour.website.com%2Fproduct-url
&#x20;    \&klevu\_productSku=ABC-123
&#x20;    \&klevu\_salePrice=123.45
&#x20;    \&klevu\_productRatings=3
&#x20;    \&klevu\_productPosition=7
:::



## Purchases/Orders Placed

The final analytics data required is when a customer makes a purchase.

If you are using the Klevu plugin for Magento, Shopify or BigCommerce, the order tracking analytics is already taken care of for you via a server-side implementation. 

:::hint{type="danger"}
**Important :** Please do not add a frontend implementation if you are using one of the these plugins, as this would result in duplicate analytics requests.
:::

****

If you are not using one of our plugins then you have two options for sending the transaction analytics data to Klevu:

1. A server-side implementation via a scheduled task.
2. Via a frontend implementation, eg. on the checkout success page.

The API call is the same for each approach, and is detailed in the [Klevu API Documentation](https://docs.klevu.com/apis/smart-search-analytics-events). It is up to you which you choose, but please only choose one. The analytics request looks like this:

:::BlockQuote
https\://stats.ksearchnet.com/analytics/productTracking
&#x20;    ?klevu\_apiKey=klevu-1234567890
&#x20;    \&klevu\_type=checkout
&#x20;    \&klevu\_productId=54321-12345
&#x20;    \&klevu\_unit=2
&#x20;    \&klevu\_salePrice=123.45
&#x20;    \&klevu\_currency=GBP
:::

This API call must be made **for each product** purchased.&#x20;

This tracking event is the same regardless of whether the customer used search or category navigation.&#x20;

Please **submit all orders to Klevu**, even if the customer didn’t use search or visit a category page.

## Category Page Views

When the customer visits a category page powered by Klevu Smart Category Navigation, it is important to inform Klevu of this activity.&#x20;

This is detailed in the [Klevu API Documentation](https://docs.klevu.com/apis/smart-search-analytics-events) and looks like this:

:::BlockQuote
https\://stats.ksearchnet.com/analytics/categoryProductViewTracking
&#x20;    ?klevu\_apiKey=klevu-1234567890
&#x20;    \&klevu\_categoryName=Sneakers
&#x20;    \&klevu\_categoryPath=Mens%3BShoes%20and%20Trainers%3BSneakers
&#x20;    \&klevu\_productIds=54321-12345%2C345
&#x20;    \&klevu\_pageStartsFrom=0
:::

## No Results Found

Even if the customer types in a query that yields no results, you should still send the analytics tracking request to Klevu. The important element to inform Klevu of a ‘no results found’ query is klevu\_totalResults=0. This applies to both quick search and the search results landing page.

:::BlockQuote
https\://stats.ksearchnet.com/analytics/n-search/search
&#x20;    ?apiKey=klevu-1234567890
&#x20;    \&term=red%20shoes
&#x20;    &**klevu\_totalResults=0**
&#x20;    \&klevu\_typeOfQuery=WILDCARD\_AND
:::



# Analytics on Modified Templates&#x20;

If you are using a modified version of a Klevu *productBlock* Template(s), be aware of the required class selectors for Analytics tracking event listening. **(This is a common oversight when extensively modifying the template).**&#x20;

:::BlockQuote
QuickSearch Product
\<li class="**klevuProduct trackProductClick** **kuTrackRecentView**" **data-id="\<%=dataLocal.id%>"**>

SearchResults Product
\<li class="**klevuProduct klevuProductClick** **kuTrackRecentView**" **data-id="\<%=dataLocal.id%>"**>
&#x20;
Other Product Link
\<a class="**klevuProduct klevuProductClick** **kuTrackRecentView**" **data-id="\<%=dataLocal.id%>"&#x20;**>

Recommendations Templates
\<li class=**"kuRECSItem kuRECSItemClick" data-id="\<%= item.id %>"**>
:::



# Testing

In order to know whether each of the tracking calls is working, you will get immediate feedback from the API response, which will look like this for successful requests:

:::BlockQuote
\<data>
&#x20;   \<response>SUCCESS\</response>
\</data>
:::

After a day or so you will start to see the analytics data appearing in the Klevu Merchant Centre, as the analytics data you provide is not processed in realtime and instead handled in batches due to the various calculations involved.


[title] Untitled
[path] /


[title] Set Custom Helpers
[path] Build UI/Templates Customizations/



Occasionally, there are requirements to add your own helper functions to the Klevu Templates. These helper functions can be used to reference local configurations, or modify existing Klevu Template functions to meet specific requirements.

## Set the Helper Function

Assign custom helpers using `setHelpers` within the Klevu options object using the following format:

:::BlockQuote
...
&#x20;  setHelpers: \{
&#x9;      "\<scope identifier(s)>": \{&#x20;
&#x9;           myHelperName: \<function()>
&#x20;         }
&#x9;}
...
:::

e.g.

:::BlockQuote
klevu(\{
&#x9;theme: \{
&#x9;	setHelpers: \{
&#x20;           "all": \{
&#x20;               helloKlevu: function()\{
&#x20;                  return 'Hello Klevu!'
&#x20;               }
&#x20;           },
&#x20;           "recs,quick": \{
&#x20;                myHelper: function()\{}
&#x20;           }
&#x20;       }
&#x9;}
});
:::



## Call the Helper Function

Reference helpers within a Klevu Template

:::BlockQuote
\<script type="template/klevu" id="anyKlevuTemplate" >
&#x20;     \<span style="color: red;">\<%= helper.helloKlevu() %>\</span>
\</script>
:::


[title] Overview
[path] Build UI/Modify Response/

# Modify Response

To modify a search response, the incoming response object is intercepted and any of the available datapoints can be manipulated as needed *prior* to being sent to the UI templates.

There are two steps:

1. *Intercept* the incoming response object
2. *Identify the data object* to be modified



## Intercept the Response Object

Any of the product attributes are available to be modified as needed or otherwise inject any custom values.

Use the `klevu.modifyResponse` function to intercept the response data.

:::BlockQuote
**klevu.modifyResponse**("\<scope>", "\<callback>");
:::



## Identify the Data Object

The simplest way to get acquainted with the available data is to use **console.log** and review the output.

:::BlockQuote
klevu.modifyResponse("landing", function(data, scope)\{
&#x20;     **console.log('klevu.modifyResponse', data);**
&#x20;});
:::

For example, the following snippet loops through **each record in the productList result** and outputs the `product` object to the browser's developer **console.log**

:::BlockQuote
klevu.modifyResponse("all", function(data, scope)\{
&#x20; klevu.each(**data.template.query.productList.result**, function(indx, product)
&#x20; \{&#xA;**&#x20;    console.log('Klevu Response Product ' + indx, product);**
&#x20; });
});
:::



## Determining Scope

**Note** that each `klevu.modifyResponse` function requires definition within the corresponding `scope` of the override. We will chart these below.

| Scope      | Description                                               |
| ---------- | --------------------------------------------------------- |
| all        | Applies to all scope modules                              |
| quick      | QuickSearch module                                        |
| landing    | SRLP module                                               |
| catnav     | Category module                                           |
| full\_page | Both SRLP and Category modules (same as "landing,catnav") |

:::hint{type="success"}
Multiple `klevu.modifyResponse` functions can be applied in the same or mixed scope.
:::



## Examples

Please see the Modify Response [Examples](docId\:Y_x07x1PW9DOw-ThixCdL) section for details of common uses.



.

[title] Set Template
[path] Build UI/Templates Customizations/



To modify a Klevu Template,  a new template is created to replace the default instance at a specific position within the interface framework. Then, indicate that Klevu should use the new template in place of the default.

There are three steps:

1. *Identify&#x20;*&#x77;hich micro-template to be replaced
2. *Create* the new template
3. *Assign the override* for the appropriate template block



## Template Identification

Klevu Theme provides a working implementation of Quick Search, Search Results Landing Page and Category Pages by just including a small JavaScript asset. All of the HTML templates are injected into your page when our JavaScript Library powers up.

In order to make efficient modifications to a template, understanding the structure and syntax will be important.

### Template Name

Klevu Template JS is built on a framework of micro-templates. The micro-templates are positioned as reusable components where applicable within the base Klevu framework.

The easiest way to understand this is to enable Template Hints. There are two steps to enable Template Hints:

- set a sessionStorage variable by opening your browser's Developer Tools, going to the Console and typing the following command:
  - `sessionStorage.setItem('klv_debugMode', true);`
- Once you have ran the above command in the Console you can append the parameter `klib_global_templateHints=true` to your URL.

This will expose the micro-template positioning, each with a red border for context as well as the associated `name` used for rendering.

e.g:
https\://www\.yourdomain.com/search/?q=blu&#x65;**\&klib\_global\_templateHints=true**


::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/2Dh2y1sYSh1AbImzaB5Ug_image.png" size="78" width="1040" height="780" caption="klib_global_templateHints=true" position="center" showCaption="true"}

The micro-templates use this identifier to render components in place by `name`

For Example, **landingProductBadge** can be called to render at multiple positions within the default  search templates.

:::BlockQuote
\<header ku-block data-block-id="ku\_landing\_result\_item\_header">
&#x20;   \<%=helper.render('**landingProductBadge**', scope, data, dataLocal) %>
\</header>
:::

Please see [Template Engine](docId\:rv82o3-Jm6NxXz8ibauUq)  for further details about `helper.render` and options



### Template ID

The Klevu theme reference script injects the micro-templates onto the webpage. The best way to view the generated templates is using the browser "Inspect Element" developer feature.

Within the website \<body> you will find Klevus template \<div> container(s) that include the scripted micro-templates. &#x20;

The micro-templates will all be of `type="template/klevu"` and will all contain a unique `id`

e.g.

:::BlockQuote
\<div id="klevu-landing-search-theme-templates" />
&#x20;\<script type="**template/klevu**" id="**klevuLandingTemplateBase**"> ... \</script>
&#x20;\<script type="**template/klevu**" id="**searchResultProductBadge**"> ... \</script>
. . .
\</div>
:::



### Template Assignment

The template `id` is assigned to the template `name` during the rendering process.

For example, the default Search Result Page (landing) Template uses the markup within the script  `id` **searchResultProductBadge&#x20;**&#x74;o render by the `name` **landingProductBadge.**



::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/7NZVnpXmh3CM0-9fUGln-_screen-shot-2023-05-31-at-82109-pm.png" size="38" width="282" height="299" caption="landingProductBadge" position="center" showCaption="true"}

:::hint{type="warning"}
**Note:** The render `name` is **not always** the same as the default micro-template `id`
:::

:::hint{type="success"}
Please see [Template Reference](docId\:B1sWNmiAoqOPOr679nW_O) for quick reference chart of template `id` to  name. As well as detail on how to view the default template markup.
:::

&#x20;&#x20;

## Create the New Template

After locating the template you wish to overwrite, it is often easiest to make a copy of the original script block and give the new copy a unique `id`. Then apply any modifications you like to the new copy.

:::hint{type="success"}
Please see [Template Reference](docId\:B1sWNmiAoqOPOr679nW_O) for detail on how to view the default template markup.
:::

For example, make a copy of the default template for displaying a product badge ...&#x20;

:::BlockQuote
\<script type="template/klevu" id="**searchResultProductBadge**">
&#x20;   \<%if(dataLocal.stickyLabelHead && dataLocal.stickyLabelHead != "") \{ %>
&#x20;       \<div class="kuDiscountBadge">
&#x20;               \<span class="kuDiscountTxt">
&#x20;                       \<%= dataLocal.stickyLabelHead %>
&#x20;               \</span>
&#x20;       \</div>
&#x20;   \<% } %>
\</script>
:::

&#x20;... and replace the `id` to something unique ...

:::BlockQuote
\<script type="template/klevu" id="**myCustom\_searchResultProductBadge**">
\<% console.log('Klevu dataLocal', dataLocal) %>
&#x20;   \<div class="kuDiscountBadge">
&#x20;       \<span class="kuDiscountTxt">
&#x20;           SHOW A CUSTOM BADGE!
&#x20;       \</span>
&#x20;   \</div>
\</script>
:::

:::hint{type="info"}
**Note:** The use of the `console.log` output for the `dataLocal` object has been provided here for reference. This is an easy way to review the product attributes available for use within the template on the browsers developer console.

Please see [Template Engine](docId\:rv82o3-Jm6NxXz8ibauUq) for further details about available data elements and options.
:::



## Assign the Override

Assign the new template `id` (`selector`) to the target render `name` within the Klevu options object using the following format.

:::BlockQuote
...
&#x9;descriptiveNameForTemplate: \{
&#x9; scope: "\<scope identifier(s)>",&#x20;
&#x9; selector: "\<id Of My Template>",
&#x9; name: "\<name Of Template To Replace>"
&#x9;},
...
:::

e.g.

:::BlockQuote
klevu(\{
&#x20; theme: \{
&#x20;   setTemplates: \{
&#x20;     myCustomTemplateDescription: \{
&#x20;       scope: "landing,catnav,quick",&#x20;
&#x20;       selector: "#idOfMyTemplate",
&#x20;       name: "nameOfTemplateToReplace"
&#x20;     },
&#x20;   }
&#x20; }
});
:::

Notice how the selector value is actually a CSS selector for your new template.&#x20;

## Determining Scope

**Note** that each `setTemplates` assignment requires definition within the corresponding `scope` of the override. We will chart these below.

| Scope      | Description                                               |
| ---------- | --------------------------------------------------------- |
| all        | Applies to all scope modules                              |
| quick      | QuickSearch module                                        |
| landing    | SRLP module                                               |
| catnav     | Category module                                           |
| full\_page | Both SRLP and Category modules (same as "landing,catnav") |



## Example

Search landing page micro-template override displaying a custom badge message.

Replaces the default markup at the **landingProductBadge** position for the **landing** scope only.

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">
/* Assign new templates to Klevu Options */
klevu({
  theme: {
    setTemplates: {
      myCustomProductBadges: { // unique name that only describes the template
        scope: "landing", // impacted scope
        selector: "#myCustom_searchResultProductBadge", // new markup block ID
        name: "landingProductBadge" // template placement name
      },
    }
  }
});
</script>

<!-- Create a new markup block with a unique 'id' -->
<script type="template/klevu" id="myCustom_searchResultProductBadge">
  <% console.log('Klevu dataLocal', dataLocal) %>
    <div class="kuDiscountBadge">
        <span class="kuDiscountTxt">
            MY CUSTOM BADGE!
        </span>
    </div>
</script>

```
:::

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/QjGONpf60dUOCqJJb2enJ_screen-shot-2023-06-01-at-92328-am.png" size="42" width="355" height="401" caption="Example" position="center" showCaption="true"}





###


[title] Examples
[path] Build UI/Modify Response/

# Modify Response

Below are some common uses of modifying the query response. You can find guides for more elaborate customizations within the **How-To** section of the Template JS documentation.

Please review : The Modify Response [Overview](docId\:k-USIa-fv-m380BqcAw7P) for complete details on the syntax used for modifying the incoming query response.



## Modify Datapoints

Product datapoints can be modified before it goes into templating.

```javascript
klevu.modifyResponse("landing", function(data, scope){
  klevu.each(data.template.query.productList.result, function(indx, product)
  {
      if (indx === 5) {
         product.salePrice = '999.00';
      }
  });
});
```



## Additional Datapoints

Custom datapoints can be added to the product response before it goes into templating. These additional points are commonly used in display or other rendering logic.

```javascript
klevu.modifyResponse("landing", function(data, scope){
  klevu.each(data.template.query.productList.result, function(indx, product)
  {
      if (indx === 5) {
         product.myFlag = true;
      }
  });
});
```


[title] Untitled
[path] Build UI/


[title] Untitled
[path] Build UI/


[title] Modify Search Query
[path] Library Reference/JS Library/Custom Overrides/

:::hint{type="warning"}
<font color="#eb144c">**IMPORTANT**</font>**&#x20;: The methods within this article are being replaced!**

Please review the following **updated** guides for efficient customization:

- [Set Template](docId:6YVX9naw6AX68WYguCOB7)
- Modify Request : [Overview](docId:_ndrEPmgAUhYltIlXkG-o)
- Modify Response: [Overview](docId\:k-USIa-fv-m380BqcAw7P)
- Modify Recommendations: [Overview](docId\:O03QERB3F-sY0BHba64Af)&#x20;
:::







To modify a search, the outgoing query to the indexed catalog is intercepted and any of the available [Klevu API ](https://developers.klevu.com/api) parameters are available to be inserted, or adjusted as needed.

There are two steps:

1. *Reference the API&#x20;*&#x74;o understand what parameters are available to meet the objective
2. *Attach the override* to the appropriate outgoing query (or queries)



:::hint{type="danger"}
Please see [Custom Overrides](docId:_bc3GcThleEaToYujDtuE)  for the prerequisite details on preparing for Klevu JS overriding.
:::

## API Referencing

Any of the [Klevu API paramters](https://docs.klevu.com/apis/smart-search) are available to be applied as needed or otherwise to override any default values.

For example, the following example snippet modifies the outgoing *productList* API Query by assigning the value of "20" as the number of filter options to return.

:::BlockQuote
klevu.setObjectPath( data , "localOverrides.query.productList.**filters.filtersToReturn.options.limit**", **20**)
:::

The object path notation corresponds to that used in the outgoing JSON API query

:::BlockQuote
"recordQueries": \[
&#x20;   \{
&#x20;     "**filters**": \{
&#x20;       "**filtersToReturn**": \{
&#x20;         "**options**": \{
&#x20;           "**limit**": **20**
&#x20;         }
&#x20;       }
&#x20;     },
&#x20;     "id": "productList",
&#x20;     "typeOfRequest": "SEARCH",
&#x20;     "settings": \{
&#x20;       "query": \{
&#x20;         "term": "jackets"
&#x20;       }
&#x20;     }
&#x20;   }
&#x20; ],
:::

See : Klevu [API documentation on Retrieving Filters](https://docs.klevu.com/apis/faceting) for more details and options



## Attaching the override

Please see [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu query overriding.

The query parameters are accessible by attaching to the query `request.control` within a previously established custom event listener.

:::BlockQuote
klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;   name: "attachToMyLandingPageOverride",
&#x20;   fire: function () \{
&#xA;**&#x20;       // Attach to the Klevu query request chain&#x20;
&#x20;       klevu.search.landing.getScope().chains.request.control.addAfter(
&#x20;       "initRequest", \{
&#x20;           name: "modifyLandingQuery",
&#x20;           fire: function (data, scope) \{

&#x20;               // OVERRIDE API PARAMETER HERE

&#x20;              &#x20;
&#x20;           }
&#x20;       });**

&#x20;       klevu(\{
&#x20;           powerUp: \{
&#x20;               landing: true
&#x20;           }
&#x20;       });
&#x20;   }
});
:::



Now the query override can be applied

:::BlockQuote
klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;   name: "attachToMyLandingPageOverride",
&#x20;   fire: function () \{

&#x20;       // Attach to the Klevu query request chain&#x20;
&#x20;       klevu.search.landing.getScope().chains.request.control.addAfter(
&#x20;       "initRequest", \{
&#x20;           name: "modifyLandingQuery",
&#x20;           fire: function (data, scope) \{

&#x20;               // OVERRIDE API PARAMETER HERE

**// SET max filter options to retrieve
klevu.setObjectPath( data , "localOverrides.query.productList.filters.filtersToReturn.options.limit", 20);**
&#x20;              &#x20;
&#x20;           }
&#x20;       });

&#x20;       klevu(\{
&#x20;           powerUp: \{
&#x20;               landing: true
&#x20;           }
&#x20;       });
&#x20;   }
});
:::

Any of the Klevu API parameters are available to be applied as needed or otherwise override any default values.

### Example

Landing page search query override to change the max filter options to retrieve for display:

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // Defer initialization (powerUp) of the Klevu component
    klevu({
        powerUp: {
            landing: false
        }
    });

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            // Attach to the Klevu query request chain 
            klevu.search.landing.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyLandingQuery",
                fire: function (data, scope) {

                    // OVERRIDE API PARAMETER HERE
                    // SET max filter options to retrieve
                    klevu.setObjectPath( data , 
                    "localOverrides.query.productList.filters.filtersToReturn.options.limit",
                    20);
                
                }
            });

 
            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });

</script>
```
:::

**Note** that the action in the above example requires definition within the corresponding scope of the override.&#x20;

| Scope   | Description        |
| ------- | ------------------ |
| quick   | QuickSearch module |
| landing | SRLP module        |
| catnav  | Category module    |

See an example below for establishing a *common function* that can be used to apply shared query modifications across multiple scope.



## Using a Common Function

Often query modifications are intended to be applied to any search query. For this reason a common function can be created in which to apply the override. This is a useful strategy to apply override parameters to every query across `quick`, `landing`, and `catnav` scope.

Please see [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu query overriding.

The query parameters are accessible by attaching to the query `request.control` within a previously established custom event listener.&#x20;

In this example we are passing the arguments to a common function object reference as *myCommonQueryOverride*

:::BlockQuote
klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;   name: "attachToMyLandingPageOverride",
&#x20;   fire: function () \{

&#x20;       // Attach to the Klevu query request chain&#x20;
&#x20;       klevu.search.landing.getScope().chains.request.control.addAfter(
&#x20;       "initRequest", \{
&#x20;           name: "modifyLandingQuery",
&#x20;           fire: function (data, scope) \{
&#xA;**&#x20;               // REFERENCE COMMON FUNCTION HERE
&#x20;               klevu.search.modules.myCommonQueryOverride(data, scope);
&#x20;              &#x20;**&#xA;&#x20;           }
&#x20;       });

&#x20;       klevu(\{
&#x20;           powerUp: \{
&#x20;               landing: true
&#x20;           }
&#x20;       });
&#x20;   }
});
:::

Now, we will define the new common function *myCommonQueryOverride&#x20;*&#x74;hat is called from the custom event listener in the previous step.

This function will loop through all outgoing queries and apply the override.&#x20;

Note the use of a dynamic `query.id` used in the loop

:::BlockQuote
(function (klevu) \{
&#x20;   klevu.extend(true, klevu.search.modules, \{
&#x20;       **myCommonQueryOverride**: function (data, scope) \{
&#x20;       klevu.each(data.request.current.recordQueries,function(key, query)\{

&#x20;       // OVERRIDE API PARAMETER HERE

**// SET active currency
klevu.setObjectPath(
&#x20;   data,
&#x20;   "localOverrides.query." + query.id + ".settings.priceFieldSuffix",
&#x20;   "GBP"
);**

&#x20;           });
&#x20;       }
&#x20;   });
})(klevu);
:::

Any of the Klevu API parameters are available to be applied as needed or otherwise override any default values.

### Example

Landing page and Quick search query common function override to change the ***Currency*** used for pricing.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

// Defer initialization (powerUp) of the Klevu components
    klevu({
        powerUp: {
            quick: false,
            landing: false,
            catnav: false
        }
    });

// QUICKSEARCH OVERRIDE

    // Define a new custom event, which will fire after Quicksearch has initialised
    klevu.coreEvent.build({
        name: "myQuickSearchOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigQuick.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myQuickSearchOverride", {
        name: "attachToMyQuickSearchOverridee",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            klevu.search.quick.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyQuickQuery",
                fire: function (data, scope) {
                    // REFERENCE COMMON FUNCTION HERE
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                 }
            });

 
            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    quick: true
                }
            });
        }
    });


// LANDING PAGE OVERRIDE

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            klevu.search.landing.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyLandingQuery",
                fire: function (data, scope) {
                    // REFERENCE COMMON FUNCTION HERE
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                 }
            });

 
            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });

//  CATEGORY PAGE OVERRIDE
    klevu.coreEvent.build({
        name: "myCategoryPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigCatnav.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });
    
    klevu.coreEvent.attach("myCategoryPageOverride", {
        name: "attachToMyCategoryPageOverride",
        fire: function () {

            // Override Query
            klevu.search.catnav.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyCatnavQuery",
                fire: function (data, scope) {
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                }
            });

            // power up
            klevu({
                powerUp: {
                    catnav: true
                }
            });
        }
    });


// COMMON FUNCTION : Overridden by all  Quick, Landing, and Catnav queries

    (function (klevu) {
    klevu.extend(true, klevu.search.modules, {
        addMyOverrideToQuery: function (data, scope) {
            klevu.each(data.request.current.recordQueries,function(key, query){ 
                
                // OVERRIDE API PARAMETER HERE
                // SET active currency
                klevu.setObjectPath(
                    data,
                    "localOverrides.query." + query.id + ".settings.priceFieldSuffix",
                    "GBP"
                );
 
            });
        }
    });
})(klevu);
</script>
```
:::









. . . . . . . . . . . .&#x20;













.

[title] Chains
[path] Library Reference/JS Library/



All chains are a list of callback functions that can be manipulated at any point in the execution. As objects are sent as a reference to a function we utilize this core js functionality to achieve the desired effect.

Klevu framework uses chains for:

- control the flow of a search instance – check search instance scope for the predefined chains
- control of the core loading  events – refer to Klevu Events docs
- custom event executions – refer to Klevu Events docs

## Understanding Chains

The concept of Chaining is derived from the promise and callback concepts in JS with some differences.

The Klevu chains where designed to work in same way callbacks work in that they are executed at a specific point in the code and will loop through a list of previously defined functions. Depending on the settings used at the time of creation of the chain any function in that chain can stop execution of future ones and return the edited result.

They are mainly used to manipulate a data object that is attached to a specific scope, both of which are being passed as object references.

The main between callbacks and chains is that , because the chains are mainly use to manipulate data the order functions that make up that chain are executed is important and so the chains will have the possibility to change the order, remove or add functions at any point in the execution chain.

**Example of a chain and what can be done with the use of interfaces:**

We have function A , B , C , D that have to be executed in that order and are added to the chain that was created , there execution will be as follows:

`A | B | C | D`

If we insert E with the **addBefore&#xA0;**&#x42; we will get an execution of

`A |``E``| B | C | D`

If we insert F with the **add&#xA0;**&#x77;e will get an execution of

`A | B | C | D |``F`

This allows for grater flexibility in the order of execution and more granulation of the code.

## Using Chains

To utilize a chain first it has to be created , to achieve this the following core interface has to be used:

```javascript
var chain = klevu.chain(<options>);
```

### Options that can be set on the chain

- **stopOnFalse&#x20;**– true/false . default false – the chain execution will stop when any element in the chain returns false
- **spacer** – numeric, default 10, the distance between the automatically added elements

### Interfaces:

- **add&#xA0;**(chainElement) – adds a new element to the chain at the end of it
- **addAfter&#xA0;**(name , chainElement) – adds a new element after the element with a specific name.
- **addBefore&#xA0;**(name , chainElement)  – adds a new element before the element with a specific name.
- **move&#xA0;**– responsible for the moving of an element , accepts an object with following attributes 
  - name – required – the name of the element to move
  - before – optional – if element has to be moved before a specific element
  - after – optional – if element has to be moved after a specific element
- **list&#xA0;**– retrieve a list of all the existing elements in the chain
- **hasData&#xA0;**– checks if data object is set
- **getData&#xA0;**– returns data object
- **setData&#xA0;**– sets new data object – this has to always be an object type
- **hasScope&#xA0;**– checks if scope object is set
- **getScope&#xA0;**– returns scope object
- **setScope&#xA0;**– sets new scope object – this has to always be an object type
- **getOptions&#xA0;**– retrieve core options and declarations of the chain



### Elements

Chain elements are attached to chains. These elements are the callback functions to be executed. Some extra options allow the modification of order the callback functions have at the time of execution.

A chain element has the following possible parameters:

- **name**: \<str> – defines name of the element, it has to be unique per chain
- **position**: \<numeric> – optional , defines the position of the element
- **fire**: \<function Source> – defines what needs to be executed, accepts 2 variables, data and scope of the chain



:::BlockQuote
box.getScope().chains.request.build.add(\{
&#x20;   name: "klevuExampleChain",
&#x20;   fire: function (data, scope) \{
...
&#x20;   }
});
:::

##





.




[title] Versioning
[path] Library Reference/



## Klevu JS Library

The core Klevu JS Library is provided on the following URL

:::BlockQuote
\<script src="https\://js.klevu.com/core/**v2**/klevu.js">\</script>
:::

Note the V2 path will always track the latest 2.x version and be the most up-to-date.&#x20;

If you prefer to lock to a specific version, you can optionally indicate the specific version within the path.

e.g.

:::BlockQuote
https\://js.klevu.com/core/2.3.9/klevu.js
:::

:::hint{type="danger"}
If you opt to lock to a specific version, you will need to manually update your version from time to time to get the latest Klevu features and bug fixes.
:::

****

## Klevu Theme Versioning

The Klevu Theme follows the same versioning process as the core Klevu JS Library 

**Quick Search:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/quick-search.js">\</script>
:::



**Search Results Landing Page:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/search-results-page.js">\</script>
:::



**Category/Collection Landing Pages:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/category-page.js">\</script>
:::



**Recommendations Widgets/Banners:**

:::BlockQuote
\<script src="https\://js.klevu.com/recs/v2/recs.js">\</script>
:::



## Klevu Template Resource Files

The following .tpl files are automatically pulled into the corresponding theme javascript during injection. They are listed here to be used as a non-minified reference.

:::hint{type="info"}
**Note:** When viewing these in the browser, use **view-source** to see the templates raw markup
:::

**Quick Search:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-templates.tpl
:::

****

**Search Results Landing Page:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/landing-templates.tpl
:::

****

**Category/Collection Landing Pages:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/catnav-templates.tpl
:::





## Debug / Development Versions

During your development you may find it easier to reference non-minified versions of the script libraries.

You can access the non-minified version of any core file by adding **debug** to the filename.

e.g.

:::BlockQuote
https\://js.klevu.com/core/v2/klevu.**debug**.js
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-search.**debug**.js
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-styles.**debug**.css
:::



## Lazy-Load Versions

If you are using Google Pagespeed Insights or Lighthouse, you might find some Klevu scripts labeld as render-blocking. Klevu provides the option to lazy-load our theme scripts which will improve your lighthouse performance score, but there is more to consider.

With lazy-load enabled, the initial script sizes are tiny. These scripts then request more resources when required, which can slightly slow the display of products compared to when lazy-load is disabled, especially after the first-page load when none of the lazy-loaded scripts are cached.

We have included lazy-load file options so you may try both settings and determine which works best for your site. 

You can access the lazy-load version of the following files by adding **lazyload** to the filename reference.

e.g.

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-search.**lazyload**.js
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/search-results-page.**lazyload**.js
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/category-page.**lazyload**.js
:::

:::hint{type="warning"}
It is not possible to have the [https://js.klevu.com/core/v2/klevu.js](https://js.klevu.com/core/v2/klevu.js) to be lazyload.&#x20;

It contains the main Klevu JS object which is used by other Klevu scripts to render the results. There is potential for conflicts with onpage objects expecting the Klevu core to be in place.
:::

**Magento users** can find lazy-load selection options within the Magento Klevu admin interface.&#x20;

*Magento admin > Stores > Configuration > Klevu > Search Configuration > Developer Settings*

See : The knowledgebase [guide for Magento lazy-loading](https://help.klevu.com/support/solutions/articles/5000877463-lazy-load-jsv2-theme-scripts) for more details.

## Combined Versions

It is very common to load the Quick Search script along with the Search Result Landing Page script or the Category/Collection Landing Page script because the Quick Search is typically available on every page of your site. Because there is some shared code within the Quick Search script and the other two scripts, Klevu also provides combined scripts that reduce the amount of JavaScript by 42% when using the combined scripts on either the Search or Category/Collection pages.&#x20;

So for example, instead of loading the Quick Search + Search Result Landing Page scripts separately on the Search page, you could load the combined script instead and reduce the download size as well as reduce the execution time of the code within the combined script on that page. The same is true on the Category/Collection Landing Pages.&#x20;

There is no benefit when loading any other pages besides Search or Category/Collection since the script for Quick Search has not changed.

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-landing-search-theme.js
:::

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-catnav-search-theme.js
:::

:::hint{type="warning"}
It is not possible to load these scripts with the automated integration available in the platform specific Klevu apps, so using these scripts requires a manual integration of the Template JS library in your site.&#x20;
:::

You can follow the [Combined Scripts](docId\:DqCuU6V1Yemu3nIK0AYqG) guide to see examples of how to integrate these combined scripts with Shopify or BigCommerce.&#x20;


[title] Combined Scripts
[path] Library Reference/JS Library/

**Use new combined scripts on Search and Category pages to improve JavaScript performance.**

Typically a Klevu Template JS integration involves adding a number of scripts. 

- **Klevu Core** (klevu.js) : this is the framework and utilities used by the Template JS library.
- **Klevu Quick Search Theme** : this is the portion of the library responsible for the search-as-you-type functionality that is added to the search input on the store. 
- **Klevu Landing Search Theme** : this is the portion of the library responsible for the search result landing page. 
- **Klevu Category Search Theme** : this is the portion of the library responsible for the category pages.

The Search Landing Page script and Category/Collection Landing Page script share almost identical JavaScript code with some small differences and they never load at the same time. However, the Quick Search script does share a lot of JavaScript code with both the Search and Category/Collection scripts, so when you are on either the search or category pages and you also have quick search loaded using individual script files you end up with some duplicated JavaScript code being downloaded and loaded in the browser. 

## Benefit

The overall code is not large, so the savings are not drastic, but there is a 42% decrease in the size of the JavaScript code when we combine quick search with either the search or category page script. 

There is no benefit when loading any other pages besides search or category since the file for quick search has not changed.

## Caveat

Unfortunately these combined scripts can only be used with a manual integration of Klevu, so you cannot use these files when using the automated integration available in the Klevu Search App.&#x20;

## Technical Overview

We have included two examples shown below in order to show how the basic logic needs to be modified from our original manual integrations in Shopify and BigCommerce. The original method included the loading of individual files for quick, search, and category. With these new combined scripts only one script is loaded in each scenario. Here is the logic:

If you are on a category page, load: *quick-catnav-search-theme.js*

Else if you are on the search page, load: *quick-landing-search-theme.js*

Else on all other pages, load: *quick-search-theme.js*

## Detailed Examples

The implementation of the combined scripts for the search and category pages involves modifying the steps outlined in the manual integration.&#x20;

### Shopify Manual Integration

The original manual integration steps for Shopify can be found by [clicking here](https://help.klevu.com/support/solutions/articles/5000874715-theme-modifications-for-jsv2-os2-dawn-?_gl=1*1jeka46*_gcl_au*MTc1MTUxMzQyMC4xNzE0MDU1NTE5*_ga*MjA5MzQ1MDMxNS4xNjgyNTQwNzE4*_ga_L5DZ4BR3P3*MTcxOTgzMzc0MC45MC4xLjE3MTk4MzUyODEuMzcuMC4w). These steps are for the Dawn theme which is an OnlineStore 2.0 theme. Below we will outline the changes necessary for Shopify.

:::hint{type="info"}
***Note:&#x20;****These steps are just for reference, so if you have already integrated Klevu you will need to make the necessary adjustments to this information that work with your theme.&#x20;*
:::

In the file called **Snippets/klevu-quick-search-theme.liquid** you will need to comment the following code:&#x20;

```html
{% comment %}
<script src="https://js.klevu.com/theme/default/v2/quick-search-theme.js"></script>

{% if template == 'page.klevu-search-results' %}
    <!-- Include Search Results Landing Page Theme -->
    <script src="https://js.klevu.com/theme/default/v2/landing-page-theme.js"></script>
{% endif %}
{% endcomment %}
```

In the file called **Snippets/klevu-metadata.liquid** you will need to replace its contents with the following code:&#x20;

```html
{% if template.name == 'collection'%}
    <script src="https://js.klevu.com/theme/default/v2/quick-catnav-search-theme.js"></script>
    <script type="text/javascript">
    var klevu_page_meta = {
        "pageType": "category",
        "categoryName": "{{collection.title | escape }}",
        "categoryUrl": "{{shop.url}}{{collection.url}}",
    };
    </script>
{% elsif template.name == 'search'%}
    <script src="https://js.klevu.com/theme/default/v2/quick-landing-search-theme.js"></script>
{% else %}
    <script src="https://js.klevu.com/theme/default/v2/quick-search-theme.js"></script>
    <script type="text/javascript">
    {% if template.name == 'cart'%}
        var cartRecords = [];
        {% for item in cart.items %}
            cartRecords.push({'itemId': {{item.variant_id}} ,'itemGroupId': {{item.product_id}} });
        {% endfor %}
        var klevu_page_meta = {
            "pageType": "cart",
            "cartRecords": cartRecords
        };
    {% elsif template.name == 'product'%}
        var klevu_page_meta  = {
            "pageType": "pdp",
            "itemName": "{{product.title | escape }}",
            "itemUrl": "{{shop.url}}{{ product.url}}",
            "itemId": "{{product.selected_or_first_available_variant.id}}",
            "itemGroupId": "{{product.id}}",
            "itemSalePrice": "{{product.price | money_without_currency}}",
            "itemCurrency": "{{shop.currency}}"
        };
    {% endif %}
    </script>
{% endif %}
```

### BigCommerce Manual Integration

The original manual integration steps for BigCommerce can be found by [clicking here](https://docs.klevu.com/template-js/get-started-with-bigcommerce#HIG4S). Below we will outline the changes necessary for BigCommerce. 

:::hint{type="info"}
***Note:&#x20;****These steps are just for reference, so if you have already integrated Klevu you will need to make the necessary adjustments to this information that work with your theme.&#x20;*
:::

In the file called **templates/layout/base.html** you will need to replace the following code:&#x20;

```html
<!-- Include Quick Search Theme -->
<script src="https://js.klevu.com/theme/default/v2/quick-search.js"></script>

{{#if page_type '===' 'search'}}
<!-- Include Search Results Landing Page Theme -->
<script src="https://js.klevu.com/theme/default/v2/search-results-page.js"></script>
{{/if}}

{{#if page_type '===' 'category'}}
<!-- Include Category Page Theme -->
<script src="https://js.klevu.com/theme/default/v2/category-page.js"></script>
<script type="text/javascript">
    var klevu_pageCategory = "{{#each breadcrumbs}}{{#unless @first}}{{name}}{{#unless @last}};{{/unless}}{{/unless}}{{/each}}";
    sessionStorage.setItem("klevu_pageCategory", klevu_pageCategory);
</script>
{{/if}}



<script type="text/javascript">
    {{#if page_type '===' 'category'}}
        var klevu_page_meta = {
            'pageType': "category",
            'categoryName':'{{#each breadcrumbs}}{{#unless @first}}{{name}}{{#unless @last}};{{/unless}}{{/unless}}{{/each}}',
            'categoryUrl': '{{category.url}}',
        };
    {{/if}}
    {{#if page_type '===' 'product'}}
        var klevu_page_meta  = {
            "pageType": "pdp",
            "itemName": "{{product.title}}",
            "itemUrl": "{{product.url}}",
            "itemId": "",
            "itemGroupId": "{{product.id}}",
            "itemSalePrice": "{{#if product.price.with_tax}}{{product.price.with_tax.value}}{{else}}{{product.price.without_tax.value}}{{/if}}",
            "itemCurrency": "{{currency_selector.active_currency_code}}"
        };

        {{#if gql.data.site.product}}
            {{#if gql.data.site.product.variants.edges.length '>' 0}}
                klevu_page_meta.itemId = "{{gql.data.site.product.entityId}}";
            {{/if}}

            {{#if gql.data.site.product.productOptions.edges}}
                {{#each gql.data.site.product.variants.edges}}
                    {{#if @index '==' 0}}
                        {{#if node.entityId}}
                            {{#if node.isPurchasable}}
                                klevu_page_meta.itemId += "-variantid_{{node.entityId}}";
                            {{/if}}
                        {{/if}}
                    {{/if}}
                {{/each}}
            {{/if}}
        {{/if}}
    {{/if}}
    {{#if page_type '===' 'cart'}}
        let klbCartRecords = [];
        fetch('/api/storefront/carts/{{cart_id}}?include=lineItems.physicalItems.options,lineItems.digitalItems.options',
            {credentials: 'include'}
        ).then(function (response) {
                return response.json();
            })
        .then(function (cartData) {
            if (!cartData || !cartData.lineItems) {
                return;
            }
            let klbCartLineItems = cartData.lineItems;
            for (let klbIndex in klbCartLineItems) {
                let klbItemTypeRows = klbCartLineItems[klbIndex];
                if (!klbItemTypeRows.length) {
                    return;
                }
                for (let klbItemRow in klbItemTypeRows) {
                    klbCartRecords.push({
                        'itemId': klbItemTypeRows[klbItemRow]['options'].length
                            ? klbItemTypeRows[klbItemRow]['productId'] + '-variantid_' + klbItemTypeRows[klbItemRow]['variantId']
                            : klbItemTypeRows[klbItemRow]['productId'],
                        'itemGroupId': klbItemTypeRows[klbItemRow]['productId'],
                    });
                }
            }
        });
        var klevu_page_meta = {
            'pageType': "cart",
            'cartRecords': klbCartRecords
        };
    {{/if}}
</script>
```

With the following code:

```html
{{#if page_type '===' 'category'}}
    <!-- Include Category Page Theme -->
    <script src="https://js.klevu.com/theme/default/v2/quick-catnav-search-theme.js"></script>
    <script type="text/javascript">
        var klevu_pageCategory = "{{#each breadcrumbs}}{{#unless @first}}{{name}}{{#unless @last}};{{/unless}}{{/unless}}{{/each}}";
        sessionStorage.setItem("klevu_pageCategory", klevu_pageCategory);        
        var klevu_page_meta = {
            'pageType': "category",
            'categoryName':'{{#each breadcrumbs}}{{#unless @first}}{{name}}{{#unless @last}};{{/unless}}{{/unless}}{{/each}}',
            'categoryUrl': '{{category.url}}',
        };
    </script>
{{else if page_type '===' 'search'}}
    <!-- Include Search Results Landing Page Theme -->
    <script src="https://js.klevu.com/theme/default/v2/quick-landing-search-theme.js"></script>
{{else}}
    <!-- Include Quick Search Theme -->
    <script src="https://js.klevu.com/theme/default/v2/quick-search.js"></script>
    {{#if page_type '===' 'product'}}
        <script type="text/javascript">
            var klevu_page_meta  = {
                "pageType": "pdp",
                "itemName": "{{product.title}}",
                "itemUrl": "{{product.url}}",
                "itemId": "",
                "itemGroupId": "{{product.id}}",
                "itemSalePrice": "{{#if product.price.with_tax}}{{product.price.with_tax.value}}{{else}}{{product.price.without_tax.value}}{{/if}}",
                "itemCurrency": "{{currency_selector.active_currency_code}}"
            };
    
            {{#if gql.data.site.product}}
                {{#if gql.data.site.product.variants.edges.length '>' 0}}
                    klevu_page_meta.itemId = "{{gql.data.site.product.entityId}}";
                {{/if}}
    
                {{#if gql.data.site.product.productOptions.edges}}
                    {{#each gql.data.site.product.variants.edges}}
                        {{#if @index '==' 0}}
                            {{#if node.entityId}}
                                {{#if node.isPurchasable}}
                                    klevu_page_meta.itemId += "-variantid_{{node.entityId}}";
                                {{/if}}
                            {{/if}}
                        {{/if}}
                    {{/each}}
                {{/if}}
            {{/if}}
        </script>
    {{else if page_type '===' 'cart'}}
        <script type="text/javascript">
            let klbCartRecords = [];
            fetch('/api/storefront/carts/{{cart_id}}?include=lineItems.physicalItems.options,lineItems.digitalItems.options',
                {credentials: 'include'}
            ).then(function (response) {
                    return response.json();
                })
            .then(function (cartData) {
                if (!cartData || !cartData.lineItems) {
                    return;
                }
                let klbCartLineItems = cartData.lineItems;
                for (let klbIndex in klbCartLineItems) {
                    let klbItemTypeRows = klbCartLineItems[klbIndex];
                    if (!klbItemTypeRows.length) {
                        return;
                    }
                    for (let klbItemRow in klbItemTypeRows) {
                        klbCartRecords.push({
                            'itemId': klbItemTypeRows[klbItemRow]['options'].length
                                ? klbItemTypeRows[klbItemRow]['productId'] + '-variantid_' + klbItemTypeRows[klbItemRow]['variantId']
                                : klbItemTypeRows[klbItemRow]['productId'],
                            'itemGroupId': klbItemTypeRows[klbItemRow]['productId'],
                        });
                    }
                }
            });
            var klevu_page_meta = {
                'pageType': "cart",
                'cartRecords': klbCartRecords
            };
        </script>
    {{/if}}
{{/if}}
```

The above code change basically replaces the loading of individual scripts for Quick, Search, and Category with the combined scripts.&#x20;

[title] Template Engine
[path] Library Reference/JS Library/



The template engine allows easy access to rendering tools that are present in the Klevu library.

## Core template functions

- **setData&#xA0;**– sets the **data** variable of the template
- **getData&#xA0;**– gets the **data** variable of the template
- **getHelpers&#xA0;**– get a full list of available template helpers
- **setHelper&#xA0;**– set new template helper or override existing one dependent on the name – setHelper: function ( name , functionSource )
- **render&#xA0;**– compile the js template based on name and return html in string format – render: function ( name /\* ,  data , dataLocal \*/ ) 
- **list&#xA0;**–  get a full list of available template names
- **setTemplate&#xA0;**– set a new template string as a template, decoded is used as a format for the templateString if set to false it will decode the template sting from base64 encoding – setTemplate : function ( templateString , name , decoded = false )
- **convertTemplate&#xA0;**– transform html string to DOM tree – return is encapsulated in a div element
- **insertTemplate&#xA0;**– append as chield a DOM node element to a parent DON node – insertTemplate : function ( parent , child )

## Template render

Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.Template functions can both interpolate values, using \<%= … %>, as well as execute arbitrary JavaScript code, with \<% … %>. If you wish to interpolate a value and have it be HTML-escaped, use \<%- … %>. 

## Global template variables

Inside the template, you have access to the following js variables:

- **data&#xA0;**– contains the returned processed data and settings of the current request in the format:
  - settings – containing settings set as part of the global context example term, landingUrl,termOriginal
  - suggestions – containing processed response of the suggestion type request, refer to the API v2 Docs for a complete format
  - query – containing processed response of the query type request, refer to the API v2 Docs for a complete format
- **dataLocal&#xA0;**– contains the object send when using micro templates. Refer to the template helper.render section
- **helper&#xA0;**– contains the list of functions defined as template functions. Core functions include:
  - **translator&#xA0;**– able to access the scope translation object in full 
  - **translate&#xA0;**– map to the scope traslator.translate 
  - **addTranslation&#xA0;**– map to the scope traslator.addTranslation
  - **getTranslation&#xA0;**– map to the scope traslator.getTranslation
  - **removeTranslation&#xA0;**– map to the scope traslator.removeTranslation
  - **setTranslations&#xA0;**– map to the scope traslator.setTranslations
  - **processCurrency&#xA0;**– map to the scope currency.processCurrency
  - **each&#xA0;**– map to klevu.each
  - **buildUrl&#xA0;**– accepts 3 arguments – example helper.buildUrl(data.settings.landingUrl,”q” , “test”)
    - uri – original url
    - key – key that needs to be changed
    - value – the value of the change
  - **stripHtml&#xA0;**– accepts 1 argument – strips any HTML tags from the input string
  - **render&#xA0;**– accepts 4 arguments
    - **name&#xA0;**– the name of the set template
    - **scope&#xA0;**– the scope the template will be rendered in
    - **data&#xA0;**– optional – will be taken from scope if not provided – data to be set in the data object of the rendered template
    - **dataLocal&#xA0;**– optional – will be defaulted to data – data to be set in the dataLocal of the rendered template

## Scope

The scope of the template engine is dependent on what Search Object Scope it is linked to. Each search object will contain as part of its scope a instance of the template engine. All data and templates are executed as part of that scope. If a user wants to use the same template in 2 or more search objects then the template has to be set for each of the template engines.

The template source can be any location where a full sting containing the template code can be extracted from , example: a element contents in main DOM , an AJAX response , an encoded variable.

Template engine accepts encoded templates in the base 64 encoding by parsing the third parameter to false(this is the default).











.


[title] Custom Overrides
[path] Library Reference/JS Library/

:::hint{type="warning"}
<font color="#eb144c">**IMPORTANT**</font>**&#x20;: The methods within this article are being replaced!**

Please review the following **updated** guides for efficient customization:

- [Set Template](docId:6YVX9naw6AX68WYguCOB7)
- Modify Request : [Overview](docId:_ndrEPmgAUhYltIlXkG-o)
- Modify Response: [Overview](docId\:k-USIa-fv-m380BqcAw7P)
- Modify Recommendations: [Overview](docId\:O03QERB3F-sY0BHba64Af)&#x20;
:::





There may be a use-case or business requirement in which a modification to the Search query or display template is needed.&#x20;

Once you have established the prerequisite code for overrides, you are free to focus on the custom action(s) necessary for your application within the Klevu scope, including [Modify Display Markup](docId:2wQzwKVdYeg1iPkBZuzv2) and [Modify Search Query](docId\:EiwwS8IBYZIcIU7fZEPrH) parameters.

This guide will familiarize with the actions involved in preparing for Template JS overrides

- *Defer* initialization (powerUp) of the Klevu component
- *Define* a new custom event
- *Listen* for the new custom event
- *Fire* the custom function, action, or override an API parameter&#x20;
- *Activate* initialization (powerUp)

**Note** that each action requires definition within the corresponding scope of the override. We will note these where applicable below.

| Scope   | Description        |
| ------- | ------------------ |
| quick   | QuickSearch module |
| landing | SRLP module        |
| catnav  | Category module    |

:::hint{type="info"}
For Klevu Recommendations there are a series of convenient [Overview](docId\:O03QERB3F-sY0BHba64Af) that can be utilized in place of these steps.
:::

****



## Defer initialization

First we need to tell Klevu not to power up the appropriate module until we integrate the overrides.  This flag will be updated at a later step.

:::BlockQuote
&#x20;powerUp: \{ **landing: false** }
:::

You can place it as an additional `options` element.

:::BlockQuote
&#x20;  klevu(\{
&#x20;      powerUp: \{
&#x20;          landing: false
&#x20;      }
&#x20;  });
:::

**Note&#x20;**&#x74;he scope of the deferred powerUp in this example is set to `landing`.

| Array name | Field Name | Description        | Default value |
| ---------- | ---------- | ------------------ | ------------- |
| powerUp    | quick      | QuickSearch module | true          |
| powerUp    | landing    | SRLP module        | true          |
| powerUp    | catnav     | Category module    | true          |



## Define a new custom event

Next we will create a new custom build event which will fire once Klevu has completed its initial setup.&#x20;

The `name` we have chosen for this example is ***myLandingPageOverride*** but you can name this whatever you like. We will use this `name` to attach it to the event lister in a later step.

:::hint{type="warning"}
**Important:** Use unique `name` value for each event to avoid conflicts!
:::

:::BlockQuote
&#x20;   **klevu.coreEvent.build**(\{
&#x20;       name: "**myLandingPageOverride**",
&#x20;       fire: function () \{
&#x20;           if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) \{
&#x20;               return true;
&#x20;           }
&#x20;           return false;
&#x20;       },
&#x20;       maxCount: 150,
&#x20;       delay: 100
&#x20;   });
:::

| Name     | Description                                         |
| -------- | --------------------------------------------------- |
| name     | Unique value used to attach it to the event lister  |
| fire     | function and logic                                  |
| maxCount | Asynchronously retry X times                        |
| delay    | Wait X milliseconds between each retry              |

This event will loop using the `maxCount` and `delay` values.

When the Klevu internal flag `setRemoteConfigLanding.build` to be set as TRUE, any attached events will fire.

**Note** that this internal `settings.flag` being checked is in the *landing* scope. A separate build event check is required for each scope in each context of the override.

| Name                         | Description                          |
| ---------------------------- | ------------------------------------ |
| setRemoteConfigQuick.build   | QuickSearch configuration is ready   |
| setRemoteConfigLanding.build | Landing page configuration is ready  |
| setRemoteConfigCatnav.build  | Category Page configuration is ready |



## Listen for the new custom event

We will now establish an event listener that is *attached* to the build event defined as ***myLandingPageOverride*** in the previous step.&#x20;

:::BlockQuote
&#x20;   **klevu.coreEvent.attach**("**myLandingPageOverride**", \{
&#x20;       name: "attachToMyLandingPageOverride",
&#x20;       fire: function () \{

&#x20;          // DO SOMETHING&#x20;

&#x20;           klevu(\{
&#x20;               powerUp: \{
&#x20;                   landing: true
&#x20;               }
&#x20;           });
&#x20;       }
&#x20;   });
:::



## Fire the custom function

Upon the myLandingPageOverride build event, we can trigger any applicable javascript within the `fire` function.

Please reference the applicable documentation sections for more detail on how to [Modify Display Markup](docId:2wQzwKVdYeg1iPkBZuzv2) or [Modify Search Query](docId\:EiwwS8IBYZIcIU7fZEPrH) parameters.&#x20;

:::BlockQuote
&#x20;   klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;       name: "attachToMyLandingPageOverride",
&#x20;       fire: function () \{
&#xA;**&#x20;          // DO SOMETHING&#x20;&#xA;**&#xA;&#x20;           klevu(\{
&#x20;               powerUp: \{
&#x20;                   landing: true
&#x20;               }
&#x20;           });
&#x20;       }
&#x20;   });
:::



## Activate initialization

Finally, now that we have completed our overrides, we can tell Klevu that we are done and allow it to power up.

:::BlockQuote
&#x20;   klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;       name: "attachToMyLandingPageOverride",
&#x20;       fire: function () \{

&#x20;          // DO SOMETHING&#x20;
&#xA;**&#x20;           klevu(\{
&#x20;               powerUp: \{
&#x20;                   landing: true
&#x20;               }
&#x20;           });**
&#x20;       }
&#x20;   });
:::







# Example

Landing page search query overrides the default limit for filter options in the result set

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // Defer initialization (powerUp) of the Klevu component
    klevu({
        powerUp: {
            landing: false
        }
    });
    

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                 return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            // DO SOMETHING
            klevu.search.landing.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyLandingQuery",
                fire: function (data, scope) {
                    // SET max filter options to retrieve
                    klevu.setObjectPath( data , "localOverrides.query.productList.filters.filtersToReturn.options.limit", 20);
                }
            });
 
            // Activate initialization (powerUp)
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });
</script>
```
:::



****













.

[title] Structure
[path] Library Reference/

The following is a basic overview of the setup and structural components used for Klevus Template JS.

### Foundation

On the webpage, a placeholder HTML \<div> with is assigned `class="klevuLanding"` as the target for displaying the search results interface.

e.g.&#x20;

:::BlockQuote
\<div class="klevuLanding">\</div>
:::



A small configuration is used for credentials and other variables specific for the implementation. See [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu) for details.

e.g.

:::BlockQuote
klevu(\{
&#x20;   url : \{
&#x20;       landing : '/search-results',
&#x20;       search: 'https\://XXXXXXX.ksearchnet.com/cs/v2/search'
&#x20;   },
&#x20;   search: \{
&#x20;       searchBoxSelector: "#my-search",&#x20;
&#x20;       apiKey: "klevu-123XXXXXXXXXXXXXX"&#x20;
&#x20;   }
});
:::



The following JavaScript files are referenced within the web page to facilitate the corresponding implementation.

**Klevu Template JS Core:**

:::BlockQuote
\<script src="https\://js.klevu.com/core/v2/klevu.js">\</script>
:::


**Quick Search:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/quick-search.js">\</script>
:::



**Search Results Landing Page:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/search-results-page.js">\</script>
:::



**Category/Collection Landing Pages:**

:::BlockQuote
\<script src="https\://js.klevu.com/theme/default/v2/category-page.js">\</script>
:::



**Recommendations Widgets/Banners:**

:::BlockQuote
\<script src="https\://js.klevu.com/recs/v2/klevu-recs.js">\</script>
:::

Note: Recommendations requires an alternate display target \<div> that is configured within the Klevu Merchant Center. See the [Getting Started with Recommnedations guide](https://help.klevu.com/support/solutions/articles/5000871419-recommendation-banner) for more details.



The basic consolidated foundation for a Search Result Landing Page would look something like this...

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/H0y5_AnI62xTv8RpYpQkh_image.png "Basic SRLP components")

### HTML Templates

&#x20;Klevu Template JS is built on a framework of reusable micro-templates.

The Klevu templates are a scripted combination of javascript and HTML. They are built upon a proprietary templating engine to avoid conflicts with other Javascript frameworks.

Data objects are passed to the script block and used for logic as well as printable expressions.

:::BlockQuote
\<script type="template/klevu" id="klevuQuickPromotionBanner">

&#x20; \<% klevu.each(data.banners, function(index, banner)\{ %>

&#x20;      \<div class="klevu-banner-ad kuBannerContainer">
&#x20;          \<a href="\<%= banner.redirectUrl %>">
&#x20;              \<img src="\<%= banner.bannerImg %>" />
&#x20;          \</a>
&#x20;      \</div>

&#x20;  \<% }); %>
&#x20;      &#x20;
\</script>
:::

Please see [Template Engine](docId\:rv82o3-Jm6NxXz8ibauUq)  for further details about `data` elements and options



The following .tpl files are automatically pulled into the corresponding theme javascript during injection. They are listed here to be used as an un-minified reference only.

:::hint{type="info"}
**Note:** When viewing these in the browser, use **view-source** to see the templates raw markup
:::

**Quick Search:**

:::BlockQuote
**view-source:**&#x68;ttps\://js.klevu.com/theme/default/v2/quick-templates.tpl
:::

****

**Search Results Landing Page:**

:::BlockQuote
**view-source:**&#x68;ttps\://js.klevu.com/theme/default/v2/landing-templates.tpl
:::

****

**Category/Collection Landing Pages:**

:::BlockQuote
**view-source:**&#x68;ttps\://js.klevu.com/theme/default/v2/catnav-templates.tpl
:::

Please see [Template Reference](docId\:B1sWNmiAoqOPOr679nW_O) for further details

****

### CSS

The following CSS file is automatically pulled into the corresponding theme javascript during injection.&#x20;

:::hint{type="info"}
**Note:** The additional **.debug** within the filename is the un-minified version used for reference only. Remove the .debug for production use.
:::

**Quick Search:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/quick-styles.**debug**.css
:::

****

**Search Results Landing Page:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/landing-styles.**debug**.css
:::

****

**Category/Collection Landing Pages:**

:::BlockQuote
https\://js.klevu.com/theme/default/v2/catnav-styles.**debug**.css
:::

See : [Styling CSS](docId:2Evmr7ofKw87yl6atYU_6)  for further details

****

### Analytics

The Klevu Template JS includes the necessary analytics reporting for searches and product clicks.

Depending on the implementation, checkout data reporting will need to be added. For the platforms supported by Klevus App/Plug-ins order data tracking is already included.

See : [Analytics/Tracking](docId\:RyZKC8NcV55-QcfjLuoHQ)  for further details













.


[title] Events callback
[path] Library Reference/JS Library/Events/



Below are some useful callback examples.

See : [Events](docId\:RkzthurSamevyEXDJZsNw)  for more detals on syntax and options

## QuickSearch

```javascript

klevu.coreEvent.attach("setRemoteConfigQuickOverride", {
    name: "attachRemoteConfigQuickOverride",
    fire: function () {
        klevu.each(
            klevu.search.extraSearchBox, function (key, box) {

                box.getScope().chains.events.focus.add({
                name: "customFocusEvent",
                fire: function (data, scope) {
                        console.log("[EVENT] Quick Search on focus event");
                    }
                });

                box.getScope().chains.events.keyUp.add({
                name: "customKeyUpEvent",
                fire: function (data, scope) {
                        console.log("[EVENT] Quick Search on keyup event");
                    }
                });

                box.getScope().chains.request.send.add({
                name: "customSendEvent",
                fire: function (data, scope) {
                        console.log("[EVENT] Quick Search send search request");
                    }
                });

                box.getScope().chains.template.render.add({
                name: "customRenderEvent",
                fire: function (data, scope) {
                        console.log("[EVENT] Quick Search results rendering")
                    }
                });

                box.getScope().chains.template.events.add({
                name: "customAfterRenderEvent",
                fire: function (data, scope) {
                        console.log("[EVENT] Quick Search results rendered")
                    }
                });


            }
        );
    }
});
```

## Template

```javascript
klevu.search.landing.getScope().chains.template.events.add({
  name: "renderResponseCustom",
  fire: function(data, scope) {

    console.log("Klevu Template rendered");

  }
});
```



.












[title] Untitled
[path] /


[title] Modify Display Markup
[path] Library Reference/JS Library/Custom Overrides/

:::hint{type="warning"}
<font color="#eb144c">**IMPORTANT**</font>**&#x20;: The methods within this article are being replaced!**

Please review the following **updated** guides for efficient customization:

- [Set Template](docId:6YVX9naw6AX68WYguCOB7)
- Modify Request : [Overview](docId:_ndrEPmgAUhYltIlXkG-o)
- Modify Response: [Overview](docId\:k-USIa-fv-m380BqcAw7P)
- Modify Recommendations: [Overview](docId\:O03QERB3F-sY0BHba64Af)&#x20;
:::







To modify a Klevu Template,  a new template is created to replace the default instance at a specific position within the interface framework. Then during powerUp, indicate that Klevu should use the new template in place of the default.

There are three steps:

1. *Identify&#x20;*&#x77;hich micro-template to be replaced
2. *Create* the new template
3. *Assign the override* for the appropriate template block

:::hint{type="danger"}
Please see [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for the prerequisite details on preparing for Klevu JS overriding.
:::



## Template Identification

Klevu Theme provides a working implementation of Quick Search, Search Results Landing Page and Category Pages by just including a small JavaScript asset. All of the HTML templates are injected into your page when our JavaScript Library powers up.

In order to make efficient modifications to a template, understanding the structure and syntax will be important.

### Template Name

Klevu Template JS is built on a framework of micro-templates. The micro-templates are positioned as reusable components where applicable within the base Klevu framework.

The easiest way to understand this is to enable Template Hints by appending the parameter `klib_global_templateHints=true` to your URL.

This will expose the micro-template positioning, each with a red border for context as well as the associated `name` used for rendering.

e.g:
https\://www\.yourdomain.com/search/?q=\***\&klib\_global\_templateHints=true**


::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/2Dh2y1sYSh1AbImzaB5Ug_image.png" size="78" width="1040" height="780" caption="klib_global_templateHints=true" position="center" showCaption="true"}

The micro-templates use this identifier to render components in place by `name`

For Example, **landingProductBadge** can be called to render at multiple positions within the default  search templates.

:::BlockQuote
\<header ku-block data-block-id="ku\_landing\_result\_item\_header">
&#x20;   \<%=helper.render('**landingProductBadge**', scope, data, dataLocal) %>
\</header>
:::

Please see [Template Engine](docId\:rv82o3-Jm6NxXz8ibauUq)  for further details about `helper.render` and options



### Template ID

The Klevu theme reference script injects the micro-templates onto the webpage. The best way to view the generated templates is using the browser "Inspect Element" developer feature.

Within the website \<body> you will find Klevus template \<div> container(s) that include the scripted micro-templates. &#x20;

The micro-templates will all be of `type="template/klevu"` and will all contain a unique `id`

e.g.

:::BlockQuote
\<div id="klevu-landing-search-theme-templates" />
&#x20;\<script type="**template/klevu**" id="**klevuLandingTemplateBase**"> ... \</script>
&#x20;\<script type="**template/klevu**" id="**searchResultProductBadge**"> ... \</script>
. . .
\</div>
:::



### Template Assignment

The template `id` is assigned to the template `name` during the rendering process.

In this example, Klevu will use the HTML within the script  `id` **searchResultProductBadge&#x20;**&#x77;here called to render by the `name` **landingProductBadge**

:::BlockQuote
setTemplate(
&#x20;   klevu.dom.helpers.getHTML("**#searchResultProductBadge**"),
&#x20;   "**landingProductBadge**",
&#x20;   true
);
:::

:::BlockQuote
\<%=helper.render('**landingProductBadge**', scope, data) %>
:::

:::hint{type="warning"}
**Note:** The render `name` is **not always** the same as the default micro-template `id`
:::

:::hint{type="success"}
Please see [Template Reference](docId\:B1sWNmiAoqOPOr679nW_O) for quick reference chart of template `id` to  `name`
:::

&#x20;&#x20;

## Create the new template

After locating the template you wish to overwrite, it is often easiest to clone the script block and give it a unique `id`. Then apply any modifications you like.

For example, the default template for displaying a product badge ...&#x20;

:::BlockQuote
\<script type="template/klevu" id="**searchResultProductBadge**">
&#x20;   \<%if(dataLocal.stickyLabelHead && dataLocal.stickyLabelHead != "") \{ %>
&#x20;       \<div class="kuDiscountBadge">
&#x20;               \<span class="kuDiscountTxt">
&#x20;                       \<%= dataLocal.stickyLabelHead %>
&#x20;               \</span>
&#x20;       \</div>
&#x20;   \<% } %>
\</script>
:::

&#x20;... Becomes ...

:::BlockQuote
\<script type="template/klevu" id="**myCustom\_searchResultProductBadge**">
&#x20;   \<div class="kuDiscountBadge">
&#x20;       \<span class="kuDiscountTxt">
&#x20;           SHOW A CUSTOM BADGE!
&#x20;       \</span>
&#x20;   \</div>
\</script>
:::

Please see [Template Engine](docId\:rv82o3-Jm6NxXz8ibauUq) for further details about available data elements and options.



## Attaching the override

Assign the new template `id` to the target render `name` within a previously established custom event listener.

:::BlockQuote
&#x20;   klevu.coreEvent.attach("myLandingPageOverride", \{
&#x20;       name: "attachToMyLandingPageOverride",
&#x20;       fire: function () \{

&#x20;       // OVERRIDE DEFAULT KLEVU MARKUP

// ASSIGN a new template here for product badge message
**klevu.search.landing.getScope().template.setTemplate(
&#x20;   klevu.dom.helpers.getHTML("#myCustom\_searchResultProductBadge"),
&#x20;   "landingProductBadge",
&#x20;   true
);&#xA;**&#xA;&#x20;           klevu(\{
&#x20;               powerUp: \{
&#x20;                   landing: true
&#x20;               }
&#x20;           });
&#x20;       }
&#x20;   });
:::

Please see [Custom Overrides](docId:_bc3GcThleEaToYujDtuE)  for details on preparing for Klevu Template overriding.



### Example 1 (landing)

Search landing page micro-template override displaying a custom badge message.

Replaces the default markup at the `landingProductBadge` position.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // Delay powerUp
    klevu({
        powerUp: {
            landing: false
        }
    });

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen in to our custom event, to make our overrides
    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {

            // OVERRIDE DEFAULT KLEVU MARKUP
            // ASSIGN a new template here for product badge message
            klevu.search.landing.getScope().template.setTemplate(
                klevu.dom.helpers.getHTML("#myCustom_searchResultProductBadge"),
                "landingProductBadge",
                true
            );

            // We're done with our overrides, tell Klevu to power up!
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });
</script>

<script type="template/klevu" id="myCustom_searchResultProductBadge">
    <div class="kuDiscountBadge">
        <span class="kuDiscountTxt">
            SHOW A CUSTOM BADGE!
        </span>
    </div>
</script>

```
:::



### Example 2 (quick)

QuickSearch micro-template override displaying a custom badge message.

Replaces the default markup at the `klevuQuickPromotionBanner` position.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // Delay powerUp
    klevu({
        powerUp: {
            quick: false
        }
    });

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myQuickSearchOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigQuick.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen in to our custom event, to make our overrides
    klevu.coreEvent.attach("myQuickSearchOverride", {
        name: "attachToMyQuickSearchOverride",
        fire: function () {

            // OVERRIDE DEFAULT KLEVU MARKUP
            // QuickSearch loop looks for any assigned searchboxes
            klevu.each(klevu.search.extraSearchBox, function (key, box) {
                // ASSIGN a new template here for promotion banner
                box.getScope().template.setTemplate(
                    klevu.dom.helpers.getHTML("#myCustom_quickPromotionBanner"),
                        "klevuQuickPromotionBanner", 
                        true
                );
            });

            // We're done with our overrides, tell Klevu to power up!
            klevu({
                powerUp: {
                    quick: true
                }
            });
        }
    });
</script>

<script type="template/klevu" id="myCustom_quickPromotionBanner">
    <div class="klevu-banner-ad kuBannerContainer">
		SHOW A CUSTOM MESSAGE!
    </div>
</script>

```
:::



### Example 3 (catnav)

Category page micro-template override displaying a custom badge message.

Replaces the default markup at the `landingProductBadge` position.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // Delay powerUp
    klevu({
        powerUp: {
            catnav: false
        }
    });

    // Define a new custom event, which will fire after the Category Page has initialised
    klevu.coreEvent.build({
        name: "myCategoryPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigCatnav.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen in to our custom event, to make our overrides
    klevu.coreEvent.attach("myCategoryPageOverride", {
        name: "attachToMyCategoryPageOverride",
        fire: function () {

            // OVERRIDE DEFAULT KLEVU MARKUP
            // ASSIGN a new template here for product badge message
            // Note : catnav and landing share the same render name and template id
            klevu.search.catnav.getScope().template.setTemplate(
                klevu.dom.helpers.getHTML("#myCustom_searchResultProductBadge"),
                "landingProductBadge",
                true
            );

            // We're done with our overrides, tell Klevu to power up!
            klevu({
                powerUp: {
                    catnav: true
                }
            });
        }
    });
</script>

<script type="template/klevu" id="myCustom_searchResultProductBadge">
    <div class="kuDiscountBadge">
        <span class="kuDiscountTxt">
            SHOW A CUSTOM BADGE!
        </span>
    </div>
</script>

```
:::



###


[title] Facet Show/Hide
[path] How To/



By default the sections within the facets menu are expanded when the page loads. Depending on the amount of filters/options, as well as the intention of the UI, it may be desired to have the menu load in an alternative state.

This guide presents two options:

1. &#x20;Default as collapsed (default and/or mobile view)
2. Toggle visibility on button click (mobile optimized)



## Default as Collapsed&#x20;

By default the facets within the menu are expanded when the page loads. Depending on the amount of facets as well as the intention of the UI, it may be desired to have each load in a collapsed state.

The following example reverses the default state so that the filters appear as collapsed.

A built in conditional check for `isMobileDevice()` identifies mobile user-agents.

```javascript
// This variable ensures we only collapse the filters on page load
var klevu_filters_collapsed = false;

// Change this value to true if you only want to collapse filters on mobile
var klevu_filters_collapsed_mobile_only = false;

klevu.afterTemplateRender('landing,catnav', function(data, scope){
  if (!klevu_filters_collapsed && (klevu.dom.helpers.isMobileDevice() || !klevu_filters_collapsed_mobile_only)) {

    // Find all filter triggers and click them to collapse them
    var filterHeaders = document.querySelectorAll('.klevuMeta[data-section="productList"] .kuFilterHead.kuCollapse');
    if (filterHeaders.length) {
        klevu.each(filterHeaders, function(key, header){
            header.click();
        });
    }          
    klevu_filters_collapsed = true;
  } 
});

```

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/wrvc1V_xIF3rkVlPbUqOt_screen-shot-2023-09-01-at-13432-pm.png" size="64" width="1020" height="866" position="center" caption="Facet Menu Collapsed on Page Load" showCaption="true"}



## Toggle Visibility on Button Click

The responsive nature of the Klevu Template re-positions the facet menu at the top of the product grid as the screen viewport is reduced to a mobile aspect ratio.

Depending on the amount of displayable facets and/or other components of the UI, it is possible the the facet menu would extend beyond the initial page view on a mobile device, even if collapsed. In this scenario, hiding the facets from initial view and then revealing them on a button trigger can be a useful modification.

The following example suppresses the facet menu on a **mobile aspect ratio**. A button is placed at the top of the product grid with a small icon and text. Triggering the button will toggle the facet menu visibility.

```html
<script type="text/javascript">

klevu({
  theme: {
    setTemplates: {
      filtersCollapsedHidden: {
        scope: "landing,catnav",
        selector: "#klevuLandingTemplateFiltersCollapsed",
        name: "filters"
      }
    },
  },
});

klevu.afterTemplateRender("landing,catnav", function(data, scope) {
  var target = klevu.getSetting(
    scope.kScope.settings,
    "settings.search.searchBoxTarget"
  );
  klevu.each(klevu.dom.find("#kuFilterOpener", target), function (
    key,
    value
  ) {
    klevu.event.attach(value, "click", function (event) {
      document
        .getElementsByTagName("body")[0]
        .classList.toggle("filter_opened");
    });
  });
});

</script>

<style>
/* CSS to show and hide filters on smaller screens, but 
  always show filters on larger screens */
.kuFilters {
  display: block;
}
#kuFilterOpener {
  display: none;
}
@media (max-width: 768px) {
  .kuFilters {
    display: none;
  }
  .filter_opened .kuFilters {
    display: block;
  }
  body .kuSearchResultsPageContainer [ku-container][data-container-id="ku_landing_main_content_left"] {
    position: relative;
    max-width: initial;
    width: 100%;
    min-height: 42px;
    display: block;
  }
  #kuFilterOpener {
    display: block;
    width: 80%;
    height: 32px;
    margin: auto;
  }
}
</style>

<!-- override template to filter button which will open close filters on the mobile -->
<script type="template/klevu" id="klevuLandingTemplateFiltersCollapsed">
  <% if(data.query[dataLocal].filters.length > 0 ) { %>
    <button id="kuFilterOpener"> 
        <svg width="14px" height="14px" viewBox="0 0 14 14" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
        <defs>
            <image width="128" height="128" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABHNCSVQICAgIfAhkiAAAA9pJREFUeJzt3c1R20AYxvEnH/foyC1KBZAKonRAB7iD0AHuIKQCnAoMFSBOOUIqQKkAuQJyWHmGMbtCkl+vvv6/mR0YGUuvvavdlex9kQAAAAAAAAAAAAAAAABgrBJJPyStJT3vlHX1WNJbdDioC0lPel3xu+Wp+ltMRCL/Gf9WWYveYBK6VP7LRoARW6p75W/LMnLMMJKq2ZjfZE6QRo0cJi61f+Vvy2Xk2KN5V/NYKumbht/6N/JX0KPsYi8kffFsP5f0yegYh1JIuqt+NpbJpvuMUfLAa7A+jk8+gNffdBjLfC/gfeCFLTXuS6BsJPuMJVFgMhtqAGOufLQQagCrmEEcwMNI9hnTtW/jx8AfX0oqJZ1q+L2Br2JKucmh1QRtU+2zybGHppSr/FXPcUS3kt0kahU1cpjIZNcAsqiRw0yu/SvfO3ZiHBK5MbBr5Rca/hwIbzhRt0ZQVs/FBCRqNxzk4syfpFO5Mb1uvM/6Cq4PdR8GTVki171vz/JS7pred60PAAAAAAAAAAAAACM014+DhyiRdFz9ftdnIIgnk3Ql/zrMR0k/NfzFueggkXSr5gs7L/oJE4dwom4rr8lZNAGJ9lt2fxU/ZFhq2u3XlWXsoGHjVPtX/nZOwFAwQrlsGsCzXGoaE3X3ATK5HEFo559erybejv1WbuR6lF2hq4U7hVPpeFl1V3MsS8/7mR3gOD51S+B8DSaYIcSsi4GkeGN2XcIKb52GGgBmItQAJpsYsSexlpwd1zzmrdNQjqBrSd81s4WSRgrPNutcQjeB7b8C23O1nATCXq4BXgYiHqsrq1LcCBqtXJz9s7ZvzqJV9IhhrmvOomvR9U9Gm5xFpfgEcLIyuW7d1yMUctfu6SED4Euhw7HNWyRxzQ4AAAAAAAAAAABgb0P5ODiV9Ln6WVTbyJMzA2eS7hX+NsxarE2YpBO5JEhNvw9HepQJWahbmpR70QhGr2uCpJeNAIY+RD7eH0lHezz/SG7imptEg6gWslka9SSSJ45S3Wyf5VE9qbsPcCa3oLHtxOuvXldQKjfrt/Ig6atn+63hMaailFtV9LvNk87V/excevaX7bG/UPEpDnCcqZRWKWLOAtu7So33F1JEOs4YtUoStTE+OP+Ve6BCDWCp7o3AN2ewbgCh2Opy5MzZRoEFpqEcQbncTZtM7bvvIrA/S6H9hXLkzFkh934VvUYhNxO1mtAs4oYOC5lsKr+IGzYsWfQC3tksxiGRu4nTtfJJYDkBXRsBlT8hidxlSdMxn25/olK5W5S7PcL2/vWir8AAAAAAAAAAAAAAAAAAYHz+Ay8t1mZnuutoAAAAAElFTkSuQmCC" id="img_1" />
        </defs>
        <g>
            <use xlink:href="#img_1" fill="#FFFFFF" stroke="none" transform="scale(0.109375 0.109375)" />
        </g>
        </svg>
        Filters
    </button>
      <div class="kuFilters" role="navigation" data-position="left" aria-label="Product Filters" tabindex="0">

        <h3 class="kuFiltersTitleHeading"><%=helper.translate("Narrow by")%></h3>
          <% helper.each(data.query[dataLocal].filters,function(key,filter){ %>
              <% if(filter.type == "OPTIONS"){ %>
                  <div class="kuFilterBox klevuFilter <%=(filter.multiselect)?'kuMulticheck':''%>" data-filter="<%=filter.key%>" <% if(filter.multiselect){ %> data-singleselect="false" <% } else { %> data-singleselect="true"<% } %>>
                      <div class="kuFilterHead <%=(filter.isCollapsed) ? 'kuExpand' : 'kuCollapse'%>">
                          <% var filter_label = (filter.label=="klevu_price") ? "price" : filter.label; %>
                          <%=helper.translate(filter_label)%>
                      </div>
                      <div data-optionCount="<%= filter.options.length %>" class="kuFilterNames <%= (filter.options.length <= 5 ) ? 'kuFilterShowAll': '' %> <%=(filter.isCollapsed) ? 'kuFilterCollapse' : ''%>">
                          <ul>
                              <% helper.each(filter.options,function(key,filterOption){ %>
                                  <li <% if(filterOption.selected ==true) { %> class="kuSelected"<% } %>>
                                      <a
                                          target="_self"
                                          href="#"
                                          title="<%=helper.escapeHTML(filterOption.name)%>"
                                          class="klevuFilterOption<% if(filterOption.selected ==true) { %> klevuFilterOptionActive<% } %>"
                                          data-value="<%=helper.escapeHTML(filterOption.value)%>"
                                      >
                                          <span class="kuFilterIcon"></span>
                                          <span class="kufacet-text"><%=filterOption.name%></span>
                                          <% if(filterOption.selected ==true) { %>
                                              <span class="kuFilterCancel">X</span>
                                          <% } else { %>
                                              <span class="kuFilterTotal"><%=filterOption.count%></span>
                                          <% } %>
                                      </a>
                                  </li>

                              <%  }); %>
                          </ul>
                          <% if(filter.options.length > 5 ) { %>
                              <div class="kuShowOpt" tabindex="-1">
                                  <span class="kuFilterDot"></span><span class="kuFilterDot"></span><span class="kuFilterDot"></span>
                              </div>
                          <% } %>
                      </div>
                  </div>
              <% } else if(filter.type == "SLIDER")  { %>
                <div class="kuFilterBox klevuFilter" data-filter="<%=filter.key%>">
                      <div class="kuFilterHead <%=(filter.isCollapsed) ? 'kuExpand' : 'kuCollapse'%>">
                        <% var filter_label = (filter.label=="klevu_price") ? "price" : filter.label; %>
                          <%=helper.translate(filter_label)%>
                      </div>
                      <div class="kuFilterNames sliderFilterNames <%=(filter.isCollapsed) ? 'kuFilterCollapse' : ''%>">
              <div class="kuPriceSlider klevuSliderFilter" data-query = "<%=dataLocal%>">
                <div data-querykey = "<%=dataLocal%>" class="noUi-target noUi-ltr noUi-horizontal noUi-background kuSliderFilter kuPriceRangeSliderFilter<%=dataLocal%>"></div>
              </div>
                      </div>
                  </div>
              <% } else { %>
                  <!-- Other Facets -->
              <% } %>
          <% }); %>

          <!-- <div class="kuFiltersFooter">
            <a target="_self" href="javascript:void(0)" class="kuBtn kuFacetsSlideOut kuMobileFilterCloseBtn" role="button" tabindex="0" area-label=""><%=helper.translate("Close")%></a>
      </div> -->


      </div>
  <% } %>
</script>

```

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/wYvffm4l-4i9OQHUFfFgb_screen-shot-2023-09-01-at-12115-pm.png" size="56" width="491" height="470" position="center" caption="Facet Toggle on Mobile View" showCaption="true"}


[title] Quick Search Element Placement
[path] How To/

Sometimes you need to have more control over the exact placement of the results for Quick Search. Luckily there is a setting in the library that allows you to specify this using any element on the page.&#x20;

```javascript
// Wait for the Klevu library to be ready
window._klvReady = window._klvReady || [];
window._klvReady.push(function(){
    klevu({
        search: {
            // Tell Klevu to use this as the target to show Quick Search results
            searchBoxTarget: document.querySelector("#myCustomTarget"),
        }
    });	

    // If Quick Search has already been initialized, rebuild it to use the new settings
    if (klevu.getObjectPath(klevu.settings, 'flags.bindLocalBoxes.build', false)) {
        klevu.rebuild.quick();
    }	
});
```

The code above will wait for the Klevu library to be loaded, then will specify the element to use for the searchBoxTarget.&#x20;

:::hint{type="warning"}
Note the value you pass to searchBoxTarget must be a reference to the element itself and not just a CSS selector.&#x20;
:::

Sometimes the Quick Search has already loaded and initialized by the time you run this code, so the example above will also rebuild Quick Search to use the new setting if needed.&#x20;


[title] How To
[path] /


[title] Customer Groups
[path] How To/



To accommodate variable ***pricing and/or visibility for specific customer group***, we will introduce two additional parameters to every API request.

- priceFieldSuffix
- visibilityGroupID

See: Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for details on preparing for Klevu JS overriding

See :  Klevu API Documentation for [Customer Groups](https://docs.klevu.com/apis/smart-search-examples#GI08Z)

# Indexing

:::hint{type="success"}
The additional currency pricing data must be supplied at the product level during catalog indexing.
:::



### XML FEED example

Below is a [FEED XML](https://github.com/klevu/feed/blob/8030b070f2b7d707791e65a2b22b2223d2c421cd/sample.xml#L518) example for specific group **visibility**

```xml
 <item>
 . . .
 
      <price>123.45 GBP</price>
      <sale_price>100 GBP</sale_price>
            
      <groups>
            <group>
                <id>vip_customer_group</id>
            </group>
      </groups>
. . .
```

Below is a [FEED XML](https://github.com/klevu/feed/blob/8030b070f2b7d707791e65a2b22b2223d2c421cd/sample.xml#L546) example for specific group visibility and/or **variable pricing**

```xml
 <item>
 . . .
 
      <price>123.45 GBP</price>
      <sale_price>100 GBP</sale_price>
            
      <groups>
            <group>
                <id>vip_customer_group</id>
                <price>49.99 GBP</price>
                <sale_price>49.99 GBP</sale_price>
            </group>
      </groups>
. . .
```

:::hint{type="info"}
If you intend to use multiple currencies in addition to group variable pricing and/or visibility, please review the Template JS [Multi-Currency](docId\:oliq0Hmh1p_A9KPKSZSqv) guide for more details
:::



# Template JS Override

The desired group visibility and/or prices are applied to all queries via overrides using the "all" `scope` value.

See: Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for details on preparing for Klevu JS overriding

### Example 1&#x20;

Exclude all records which do not belong to the group

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

    // The selected customer group <id> 
    var klevu_loginCustomerGroup = 'vip_customer_group';


    klevu.modifyRequest("all", function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, "settings.visibilityGroupID", klevu_loginCustomerGroup);
      });
    });
    
 
</script>
```

BigCommerce

```html
<script type=“text/javascript”>

  // the group id of the currently logged in customer
  var klevu_loginCustomerGroupId = '{{customer.customer_group_id}}' ? '{{customer.customer_group_id}}' : '';
  var klevu_loginCustomerGroup = klevu_loginCustomerGroupId ? 'groupid_' + klevu_loginCustomerGroupId : '';
  
  // only modify the requests when there is a valid customer group id
  if (klevu_loginCustomerGroupId) {
     klevu.modifyRequest('all', function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, "settings.visibilityGroupID", klevu_loginCustomerGroup);
      });
     });
   }
   
</script>
```
:::

| **API Parameter** | **Description**                                      | **Format** |
| ----------------- | ---------------------------------------------------- | ---------- |
| visibilityGroupID | Exclude all records which do not belong to the group | \{GROUPID} |

See :  Klevu API Documentation for [Customer Groups](https://docs.klevu.com/apis/smart-search-examples#GI08Z)



### Example 2

Apply the specific customer group pricing for the appropriate currency

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

/* IMPORTANT FOR BIGCOMMERCE APP USERS, INDEXING THROUGH KLEVU PLUGIN ONLY,
REFER TO BIGCOMMERCE TAB */
  
// the currency and group of the currently logged in customer
  var klevu_currency = 'GBP';
  var klevu_loginCustomerGroup = 'vip_customer_group';
 
   klevu.modifyRequest("all", function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, "settings.priceFieldSuffix", klevu_currency + '-' + klevu_loginCustomerGroup);
      });
   });
 
</script>
```

BigCommerce

```javascript
<script type="text/javascript">

  // the currency and group of the currently logged in customer
  var klevu_currency = '{{currency_selector.active_currency_code}}';
  var klevu_loginCustomerGroupId = '{{customer.customer_group_id}}' ? '{{customer.customer_group_id}}' : '';
   
  // only modify the requests when there is a valid customer group id 
  if (klevu_loginCustomerGroupId) {
     klevu.modifyRequest('all', function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, 'settings.priceFieldSuffix', klevu_currency + '-groupid--' + klevu_loginCustomerGroupId);
      });
     });
   }
 
</script>
```
:::

| **API Parameter** | **Description**                                    | **Format**             |
| ----------------- | -------------------------------------------------- | ---------------------- |
| priceFieldSuffix  | Fetch prices/currency specific to a customer group | \{CURRENCY}-\{GROUPID} |

See :  Klevu API Documentation for [Customer Groups](https://docs.klevu.com/apis/smart-search-examples#GI08Z)

[title] Introduction
[path] /

## Overview

Klevu's Template JS (often referred to as JSv2/JS Library) offers a quick and efficient solution for implementing a Search Query and Result display interface.

The UI is based on a proprietary JavaScript engine that injects all necessary markup and functionality onto a given webpage.

Through a few lines of reference code, Klevu Search can be incorporated by an effort no greater than Cut, Paste, and Configure.

Once this foundation is in place, all elements can be modified as needed to meet specific business or display requirements. Including all HTML for structure, JavaScript for custom functionality, and of course, any CSS for styling.&#x20;

The UI is based on a proprietary JavaScript engine that injects all necessary markup and functionality onto a given webpage. Its design will not conflict with other JavaScript frameworks (JQuery, etc), but rather the elements are exposed to work together with these frameworks if needed.

The Klevu Template JS facilitates the Search, Result, and Analytics communication to Klevu.  Catalog Indexing can be handled via the API, XML, Feed or one of our platform specific applications.&#x20;

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/fv8vQgXFjnN7BblH6Bkbs_image.png" size="80" width="1219" height="541" position="center" darkWidth="800" darkHeight="355" showCaption="false"}



## Search Query API

Search Query communication with the corresponding Klevu Index is handled via [Klevu API](https://docs.klevu.com/apis).

The Template JS is responsible for "finding and binding" to the targeted Search \<input> field(s) on the webpage. The Search \<input> fields, corresponding Index id, and API Endpoint are defined within the core configuration options of the Template JS.  See: [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu)  for more details.

The search phrase is picked up from the corresponding \<input> by this listener and sent to Klevu using Klevus Search API JSON structure. &#x20;

The corresponding response of relevant matching data is returned in JSON format and used to render display on the page.

## JS Library

Template JS is based on a core JavaScript Library and accompanying "Theme" resources.

**klevu.js** - The Template JS core functions

**quick-search.js** - The default 'Theme' quick search modal display markup, stylings, and supporting functions

**search-results-page.js** - The default 'Theme' search results landing page display markup, stylings, and supporting functions

**category-page.js** - The default 'Theme' category landing page display markup, stylings, and supporting functions

**klevu-recs.js** - Core JS supporting configured Recommendations banners

See:  [Structure](docId\:pUmT_E7JdsEaf0Pa2FM8F) for more details

## HTML Templates

The JSON object of a search response is captured within the Template JS core functions and used to render display on the page.&#x20;

The display layout and styling (or 'Theme') consists of individual scripted HTML micro-templates. Each micro-template is assigned a space in the result display skeleton. Templates can be included into other templates, reused in loops, etc.

All the markup within the templates are assigned class attribute values to facilitate listening events as well as styling via corresponding CSS

See:  [Structure](docId\:pUmT_E7JdsEaf0Pa2FM8F) for more details

## Analytics API

**Analytics is extremely important in Klevu Search**. It is **required** for all integrations and should not be considered an optional element.

It is one of the key drivers behind Klevu Machine Learning; tracking customer searches and clicks to feed into our AI for relevant search results based on real customer interactions.

- Searched terms
- Products clicked
- Orders placed

Note: If you are using the Klevu plugin for Magento, Shopify or BigCommerce, the **orders placed tracking** aspect of analytics likely already taken care of for you via a server-side implementation.

See:  [Structure](docId\:pUmT_E7JdsEaf0Pa2FM8F) for more details



[title] Translated or Edit Text
[path] How To/

Sometimes, you need to change Klevu's default text. We can do this using Klevu's translation engine. Below is an example of how to setup translations that will get merged into the default Klevu translations for any language.&#x20;

```javascript
<script>

var klevu_lang = 'it';
var klevu_custom_translations: {
    "en": {
          
    },
    "fr": {
        "Price: High to low": "Prix décroissant",
        "Price: Low to high": "Prix croissant",
        "Narrow by": "Filtrer par",
        "Relevance": "Pertinence",
    }
};

var klevu_storeTranslations = klevu_custom_translations[klevu_lang];

</script>

<script src="https://js.klevu.com/core/v2/klevu.js"></script>

```

## More Information about Translations in Klevu

Klevu templates wrap text that is used in a translate helper as shown below:

```javascript
<%= helper.translate("Load More")%>
```

In the above example, you could translate or modify this text to be anything you want by simply specifying a different value for "Load More".&#x20;

:::hint{type="warning"}
The translation works with the ***EXACT*** string of text passed into the translate function, so ensure you ***use the exact same case, including any spaces or special characters*** that were passed into the translate function.

**Examples:**

"\<b>%s\</b> productList" => notice it has special characters and spaces

" Results" => notice there is a space at the begining.&#x20;
:::

If you wanted to translate the words "Load More" for the template example shown previously to something like "Show More" or you want it to be in some other language altogether, you would use something as simple as this:

```javascript
var klevu_storeTranslations = {
    "Load More": "Show More",
};
```

The example at the begining of this article shows how you could add translations to support multiple languages.&#x20;

[title] Add-To-Cart Function
[path] How To/



The actual method to add items to the cart/checkout workflow varies by platform. This guide will show you where to locate the Klevu Add-To-Cart function if you should need to make adjustments, or write your own functionality.

## General Use

The Klevu Add-To-Cart button calls the function ***klevu\_addtocart***

:::BlockQuote
&#x20;/\*
&#x20; \* id  : product ID
&#x20; \* url : product page URL
&#x20; \* qty : desired quantity (default 1)
&#x20; \*/
&#x20; function klevu\_addtocart( id, url, qty ) \{  &#x20;
&#x20;   // Add-To-Cart logic here
&#x20; }
:::

****

**Example**

Simply implement the function ***klevu\_addtocart*** with your own logic of what you would like to happen when a customer clicks on Add-To-Cart.

Enabling the button and/or changing the button text can be done using variables as presented below.

```javascript
<script type="text/javascript">

  klevu_addToCartEnabled = true;      // or false to disable

  klevu_uc_userOptions = {
	 	addToCartButton: 'Add To Bag!'  	// Custom button text
  }
	
  function klevu_addtocart( id, url, qty ) {
    // Add your logic here!
  }
</script>
```



## Klevu Recommendations

The Klevu Recommendations Add-To-Cart function call contains an extra argument `recsKey` to identify the specific recommendations banner from where the click originated.

```javascript
<script type="text/javascript">

  function klevu_addtocart( id, url, qty, recsKey ) {

      if ( recsKey == 'abc-123-xyz-321' ) {
        // Add a specific recommendation logic here!
        
      } else {
        // Add your logic here!
        
      }
    
  }
</script>
```



## Supported Klevu Apps / Extensions

If you are already using Klevu Search via a Klevu App/Extension, you may find that the Add-To-Cart button within the Klevu Templates or Recommendations is already set and operational.

:::hint{type="danger"}
There should be no need to further modify these functions. They are included below for reference.
:::



### Shopify

**Configure in KMC :** Smart Search → Customizations → Add To Cart

**Function location :** *snippets/klevu-add-to-cart*

```javascript
<script type="text/javascript">
    if ('undefined' === typeof klevu_addtocart) {
        function klevu_addtocart( id, url, qty ) {
            if ('undefined' !== typeof klevu_customAddToCart) {
                klevu_customAddToCart(id, url, 1);
            } else {
                var urlProtocol = ( "https:" === document.location.protocol ? "https://" : "http://" );
                var url = urlProtocol + window.location.hostname + '/cart/add?id=' + id + '&quantity=1';
                window.location.assign(url);
            }
        }
    }
</script>
```

**Note:** You can use the provided check for `klevu_customAddToCart()` ( line 5 above ) for custom cart functionality



### BigCommerce

**Configure in KMC :** Smart Search → Customizations → Add To Cart

**Function location :&#x20;***templates/components/klevu/klevu-add-to-cart.html*

```javascript
<script type="text/javascript">
  function klevu_addtocart( id, url, qty ) {
    if( 'undefined' !== typeof klevu_customAddToCart ){
      klevu_customAddToCart( id, url, qty );
    } else{
      var urlProtocol = ( "https:" === document.location.protocol ? "https://" : "http://" );
      var url = urlProtocol + window.location.hostname +'/cart.php?action=add&product_id='+id;
      window.location.assign(url);
    }
}
</script>
```

**Note:** You can use the provided check for `klevu_customAddToCart()` ( line 4 above ) for custom cart functionality



### Magento

**Configure in KMC :** Smart Search → Customizations → Add To Cart

**Enable in Magento Admin :** Stores → Configuration → Klevu → Search Configuration → Add to Cart Button

**Function location :** *vendor/klevu/module-addtocart/view/frontend/templates/klevu/addtocart/index.phtml*

```php
<?php if ($block->isAddtocartEnabled()): ?>
    <script type="text/javascript">
        function klevu_addtocart(id, url, qty) {
            var el = document.createElement("a");
            el.setAttribute(
                "data-post",
                '{' +
                '"action": "<?= $block->escapeUrl($block->getUrl('checkout/cart/add')) ?>",' +
                '"data": {"product":"' + id + '", "qty":"' + qty + '"}' +
                '}'
            );
            el.style.width = "0px !important";
            el.style.height = "0px !important";
            document.body.appendChild(el);
            el.click();
            document.body.removeChild(el);
        }
    </script>
<?php endif; ?>
```

:::hint{type="warning"}
If modifications are required, it is strongly recommended to properly extend the Klevu module to avoid potential conflicts during future updates to the system.
:::



### SalesForce Commerce Cloud

**Configure in KMC :** Smart Search → Customizations → Add To Cart

```javascript
<script type="text/javascript">
function klevu_addtocart( id, url, qty ) {
            $.spinner().start();
            var addToCartUrl = 'https://development-web-demandware.net/on/demandware.store/Sites-xx-Site/default/Cart-AddProduct';
            var form = {
                pid: id,
                quantity: 1
            };
            
            $.ajax({
                url: addToCartUrl,
                method: 'POST',
                data: form,
                success: function (data) {
                    $.spinner().stop();
                },
                error: function () {
                    $.spinner().stop();
                    window.location.replace(url);
                }
            });
        }
</script>
```




[title] Untitled
[path] Build UI/


[title] Facet Option Order
[path] How To/



By default, Klevu will return the facet options in a sort order based on the number of records each option has in the result ("Frequency").  An alternative is to list the options in "Alphabetical" order.

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/oXFEe5lg_braILnyVnYPW_screen-shot-2023-07-21-at-124605-pm.png" size="88" width="873" height="518" position="center" caption="Frequency vs Alphabetical Option Ordering" showCaption="true"}



Klevu's search API query can be modified to allow for alphabeticaly listing the facet options using "INDEX" as the `options.order` value. &#x20;

**Modifying the request in this way will apply to all facets.**

```javascript
klevu.modifyRequest("landing,catnav", function(data, scope){
  klevu.each(data.request.current.recordQueries, function(key, query){
    klevu.setObjectPath(query, "filters.filtersToReturn.options.order", "INDEX");
  });
});
```

| **&#x20;Parameter Value** | **Description**                                                                 |
| ------------------------- | ------------------------------------------------------------------------------- |
| FREQ                      | Sort the options based on the number of corresponding records in the result set |
| INDEX                     | Sort the options alphabetically                                                 |

See : Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for more details.



## Ordering Options for a Specific Facet

There may be instances where a specific facet can benefit from Alphabetical sorting apart from the frequency default.

The below example will modify a specific facet and sort the `filter.options` in Alphabetical order for the `filter.key` "category"

```javascript
klevu.modifyResponse("landing,catnav", function(data, scope){

  /* loop through filters in the response */
  
  klevu.each(data.template.query.productList.filters, function(indx, filter)
  {
      if (filter.key === 'category') {
		  
		/* JS sort object by 'name' value */
		filter.options.sort(function (a, b) {
			if (a.name < b.name)  return -1;
			if (a.name > b.name)  return 1;
			return 0;
		});
		  
      }
  });
});
```

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/RvrrLElwWikm7Rp1AlTXi_screen-shot-2023-07-21-at-24921-pm.png" size="34" width="283" height="518" position="center" caption="&#x22;Category&#x22; options sorted alphabetically" showCaption="true"}



## Predefined Option Ordering

There may be instances when neither Frequency ("FREQ") or Alphabetical ("INDEX") sorting is sufficient.&#x20;

A common use-case is a facet for **Size**.  A predetermined option sorting for **Size** can be set for an order in which retail shoppers are accustomed.

### Example 1

This example sets the `filter.options` to a predetermined order for the `filter.key` "size".

:::hint{type="warning"}
**Important :** All available facet options should be included to accommodate variances within the results.

Also, consider case sensitivity as it applies.
:::

```javascript
klevu.modifyResponse("landing,catnav", function(data, scope){

  /* loop through filters in the response */
  
  klevu.each(data.template.query.productList.filters, function(indx, filter)
  {
      if (filter.key === 'size') {
		  
		/* set desired order for 'size' facet options */
		const optionOrder = ["X Small","Small","Medium","Large","X Large"];

		optionOrder.reverse().forEach(function(elm) {
			
			/* JS sort object by 'name' matching the optionOrder value */
			filter.options.sort(function (a, b) {
				if (a.name === elm)  return -1;
				if (a.name !== elm && b.name !== elm)  return 0;
				return 1;
			});

		});
		  
      }
  });
});
```

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/t87RdJmQbaJFu46M2dzCm_screen-shot-2023-07-21-at-15810-pm.png" size="50" width="347" height="171" position="center" caption="Predefined Option Order" showCaption="true"}

### Example 2

This example sets the facet options to a predetermined order for the `filter.key` "size", but also considers any range of numerical sizes as well.&#x20;

The following snippet:

- Separates the the alphabetic from the numeric filter option values (based on `name`)
- Sets the `alphabetic` object to the defined sort order (`optionsOrder`).
- Sorts the `numeric` object to numerical order
- Concatenates the two objects prior to setting to the `filter.options`&#x20;

:::hint{type="warning"}
**Important :** All available facet options should be included to accommodate variances within the results.

Also, consider case sensitivity as it applies.
:::

```javascript
klevu.modifyResponse("landing,catnav", function(data, scope){

  /* loop through filters in the response */
  
  klevu.each(data.template.query.productList.filters, function(indx, filter)
  {
      if (filter.key === 'size') {
				  
		/* set desired order for 'size' facet options */
		const optionOrder = ["X Small","Small","Medium","Large","X Large"];

		
		/* get the filter options that are NOT numeric */
		
		const alphabetic = filter.options.filter(value => {
			return isNaN(value.name)
		});
		
		/* sort object by 'name' value matching desired sortOrder */
		optionOrder.reverse().forEach(function(elm) {
		
			alphabetic.sort(function (a, b) {
				if (a.name === elm)  return -1;
				if (a.name !== elm && b.name !== elm)  return 0;
				return 1;
			});
		
		});

		/* get the filter options that ARE numeric */
		const numeric = filter.options.filter(value => {
			return !isNaN(value.name)
		});
		  
		/* sort object by 'name' value ascending */
		numeric.sort(function (a, b) {
			var numberOptionA = +a.name ? +a.name : 1000;
			var numberOptionB = +b.name ? +b.name : 1000;
			return numberOptionA - numberOptionB
		}); 

		/* concatenate the two sorted objects */
		const orderedOptions = numeric.concat(alphabetic);


		filter.options = orderedOptions;

      }
  });
});
```

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/bhLKKYpar5vTDZZezTXAd_screen-shot-2023-07-21-at-23503-pm.png" size="42" width="346" height="412" position="center" caption="Example 2" showCaption="true"}


[title] Recs Fallback Query
[path] How To/



In some cases,  it can be desirable to apply a "fallback" query to Smart Recommendation banners where the applied logic might equate to no results found.

**For example:** when first installing Smart Recommendations "Checkout/Cart" logic for "Also bought Together" banners, there may not be enough initial data to qualify a result.

Any of the API options for [Smart Recommendations](docId:4LOFui8shVdj88SWA1YzG) can be applied to the fallback query.



### Example

In the example below, a "Trending Products" (`RECS_TRENDING`) query replaces the target Recommendations banner if no results are found.

**Note**: Apply the target klevu-recs banner `id` to the `klevu_recsFallBackId` variable.

**Note:** Also adjust the `templateData.metadata.title` to match the intent of the fallback query.

```javascript
var klevu_recsFallbackId = "< ADD YOUR TARGET KLEVU-RECS ID HERE >";
var klevu_recsFallback = false;

/* Observer for record queries */
function klevu_processRECSRecordQueries(recordQueries, recsKey)
{
    var recsQuery = recordQueries[0];

    /* apply only to the specified banner recsKey */
    if (recsKey == klevu_recsFallbackId) {
    
        klevu.setObjectPath(recsQuery, "settings.fallbackQueryId", "myFallbackQuery");
        
        var myFallbackQuery = {
                      "id": "myFallbackQuery",
                      "isFallbackQuery": true,
                      "fallbackWhenCountLessThan": 1,
                      "typeOfRequest":"RECS_TRENDING",
                      "settings":{"typeOfRecords":["KLEVU_PRODUCT"],"limit":10}
        }
        
        recordQueries[1] = myFallbackQuery;
      
    }
}


/* Observer for query results */
function klevu_processRECSQueryResults(queryResults, recsKey) {
    
    /* apply only to the specified banner recsKey */
    if (recsKey == klevu_recsFallbackId) {
                    
        if (queryResults[0].meta.totalResultsFound == 0) {
            
          klevu_recsFallback = true;
            
          /* replace main results with fallback results */
          queryResults[0] = queryResults[1];
          queryResults[0].id = "klevuRECSItemList";
          
        }
    }
}

/* Observer to process template data */
function klevu_processRECSTemplateData(templateData, recsKey) {
        
    /* apply only to the specified banner recsKey */
    if (recsKey == klevu_recsFallbackId && klevu_recsFallback) {
                
        /* replace the title as desired (based on Fallback intent) */
        templateData.metadata.title = 'Trending Products (as Replacement)';
  
    }
}
```

See : [Overview](docId\:O03QERB3F-sY0BHba64Af) for more details on the functions used in the above example.


[title] Examples
[path] Build UI/Modify Request/

# Modify Request

Below are some common uses of modifying the query request. You can find guides for more elaborate customizations within the **How-To** section of the Template JS documentation.

Please review : The Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for complete details on the syntax used for modifying the outgoing query.



## Facet/Filter Options Count

Increase the default maximum number of filter options (10) to "20" for every query.

```javascript
klevu.modifyRequest("all", function (data, scope) {
  klevu.each(data.request.current.recordQueries, function (key, query) {
    klevu.setObjectPath(query, "filters.filtersToReturn.options.limit", 20);
  })
});
```

| **API Parameter** | **Description**                                                  |
| ----------------- | ---------------------------------------------------------------- |
| options.limit     | Specify the maximum number of options to be included per filter. |

See : Klevu [API documentation on Retrieving Filters](https://docs.klevu.com/apis/faceting) for more details and options




## Run-time Boosting

Influence the relevancy algorithm by assigning `weight` to different aspects at the time of query.

```javascript
klevu.modifyRequest("landing","productList.boost.filters", [
  {
    "key": "brand",
    "values": ["ACME"],
    "weight": 200
  }
]);
```

| **API Parameter** | **Description**                                         |
| ----------------- | ------------------------------------------------------- |
| boost             | Query-level aspects to influence the relevancy rankings |

See : Klevu API [Personalisation](docId\:YFU114Puw2lTVF05GaFWv) for more details and more options

##

## Constrain Result Set (Advanced Filtering)

You can add a `groupCondition` to restrict the result set to specific attributes and values. This constraint is typically applied "behind the scenes" to create specialized result set experiences.

Some examples include:

- Brand specific listings
- Curated landing pages
- Automotive fitment

```javascript
klevu.modifyRequest("landing","productList.settings.groupCondition", {
    "groupOperator": "ALL_OF",
    "conditions": [
        {
            "key": "brand",
            "valueOperator": "INCLUDE",
            "values": [
                "ACME"
            ]
        }
    ]
});
```

| **API Parameter** | **Description**                                                    |
| ----------------- | ------------------------------------------------------------------ |
| groupOperator     | Defines the condition of filtering (`ALL_OF`, `ANY_OF`, `NONE_OF`) |
| conditions        | The array of attributes (`key`) to apply to the condition          |

See : Klevu API [Advanced Filtering](docId\:RbT4zzdIHEIp1lCuk8n-r) for more details and more options

[title] Overview
[path] Build UI/Modify Recommendations/



# Modify Recommendations&#x20;

:::hint{type="info"}
This guide is for working with the Klevu API Request and Response data for Klevu Smart Recommendations.  Direct editing of the display markup is achieved within the Klevu Merchant Center.

Please review the Knowledge Base article for more details on [how to work with the Recs Template Editor](https://help.klevu.com/support/solutions/articles/5000871328-templates)
:::



It is possible to modify the Klevu Recommendations query, response, or template data for any or all of your Recommendation banners. You can do this by adding one or more of the following hook functions, after the Klevu initialization.

Within each of these hook functions, you will find relevant objects and variables that you can use to modify the default behavior provided by Klevu. 

**Note:** the `recsKey` value is the `id` provided with each Recommendation banner. This value can be used to specifically target a specific banner for modification.

## Modify Recs Request

Any of the [Klevu API parameters](https://docs.klevu.com/apis/smart-search) are available to be applied as needed or otherwise to override any default values within the `recordQueries` object

:::BlockQuote
function klevu\_processRECSRecordQueries(recordQueries, recsKey) \{
&#x20; console.log(recordQueries, recsKey);
}
:::



## Modify Recs Response

Any of the *product* attributes are available to be modified as needed or otherwise inject any custom values via `queryResults`

:::BlockQuote
function klevu\_processRECSQueryResults(queryResults, recsKey) \{
&#x20; console.log(queryResults, recsKey);
}
:::



## Modify Recs Template Data

Any of the *template* attributes are available to be modified as needed or otherwise inject any custom values via `templateData`

:::BlockQuote
function klevu\_processRECSTemplateData(templateData, recsKey) \{
&#x20; console.log(templateData, recsKey);
}
:::



## After Recs Render

After the Recommendations template renders, any custom JavaScript action can be executed

:::BlockQuote
function klevu\_bindRECSTemplateElementEvents(templateData, recsKey) \{
&#x20; console.log(templateData, recsKey);
}
:::



## Recs Item Click Event

OnClick of an item within the Recommendations banner any custom JavaScript action can be executed

:::BlockQuote
function klevu\_RECSItemClick(templateData, itemId, recsKey) \{
&#x20; console.log(templateData, itemId, recsKey);
}
:::



## Examples

Please see the Modify Recommendations [Examples](docId\:dX6yJaCsBv_cXuXcrcZJI) section for details of common uses.




[title] Untitled
[path] /


[title] BigCommerce
[path] Getting Started/Apps/Plug-ins/



There are two options for implementing the Klevu Template JS on BigCommerce:

1. Automated via the Klevu BigCommerce App (available from the BigCommerce Marketplace)
2. Manual implementation of the files into the BigCommerce Theme

Manual install may be required for the following conditions:

- Your BigCommerce Theme has been modified or is otherwise preventing the Klevu App automation
- You are installing Klevu on a preview theme

## Marketplace App

If you are using a version of Klevu app installed *before* December 2021, please contact support for information about migrating to Klevu TemplateJS.

You can find detailed installation steps on the Klevu Knowledge base article for [BigCommerce Integration](https://help.klevu.com/support/solutions/articles/5000871271-integration-steps-for-bigcommerce)

Once installed, the template JS resources will be available as placed automatically by the <font color="#eb144c"> </font>available in the BigCommerce Marketplace.

The following is a summary of automated steps as part of the Big Commerce App<font color="#eb144c"> </font>installation:&#x20;

1. Places code reference files into ***templates/components/klevu***
   - head-scripts.html (main reference)
   - klevu-js-init.html (config/options)
   - klevu-add-to-cart.html (button functionality)
   - klevu-search-theme.html (search results)
   - klevu-catnav-theme.html (category results - if applicable)
   - klevu-recommendations.html (recommendations core - if applicable)
   - klevu-metadata.html (recommendations support - if applicable)
2. Adds core include to ***layout/base.html***
3. Adds display target \<div> in ***pages/search.html***
4. Adds display target \<div> in ***pages/category.html&#x20;***(if applicable)
5. Authorizes BC API for hourly Catalog Synchronization



## Manual Installation

If your BigCommerce Theme has been modified or is otherwise preventing the above automation, you can manually install Klevu Template JS using the steps below, or any variation of it that fits your architecture

:::hint{type="danger"}
We recommend implementing these steps on an unpublished theme to avoid any unforeseen conflicts with the live site.
:::



### Core and Configuration

Please see [Quickstart : Smart Search](docId\:AMGa2LZ3adsU1tVJxhg1K) for detailed instructions on incorporating core JavaScript and `klevu.interactive`

****

**Include the core files according to page\_type**

```javascript
<!-- Include Klevu JavaScript Library -->
<script src="https://js.klevu.com/core/v2/klevu.js"></script>

<!-- Include Quick Search Theme -->
<script src="https://js.klevu.com/theme/default/v2/quick-search.js"></script>

{{#if page_type '===' 'search'}}
<!-- Include Search Results Landing Page Theme -->
<script src="https://js.klevu.com/theme/default/v2/search-results-page.js"></script>
{{/if}}

{{#if page_type '===' 'category'}}
<!-- Include Category Page Theme -->
<script src="https://js.klevu.com/theme/default/v2/category-page.js"></script>
<script type="text/javascript">
    var klevu_pageCategory = "{{#each breadcrumbs}}{{#unless @first}}{{name}}{{#unless @last}};{{/unless}}{{/unless}}{{/each}}";
    sessionStorage.setItem("klevu_pageCategory", klevu_pageCategory);
</script>
{{/if}}
```

****

**Configure Klevu Options to fit your theme**

```javascript
<!-- Initialise Klevu for your store -->
<script type="text/javascript">
    klevu.interactive(function () {
        var options = {
            url : {
                protocol: 'https:',
                queryParam: 'search_query',
                landing: '/search.php', // your BigCommerce Search Results Page
                search: 'https://eucsXXXv2.ksearchnet.com/cs/v2/search' // your Klevu APIv2 Search URL + endpoint path
            },
            search: {
                minChars: 0,
                searchBoxSelector: "#search_query", // your BigCommerce Search Input
                apiKey: "klevu-XXX" // your Klevu JS API Key
            },
            analytics: {
                apiKey: 'klevu-XXX' // your Klevu JS API Key
            }
        };
        klevu(options);
    });
</script>
```

:::hint{type="info"}
Note:  the `klevu.interactive` configurations should be set globally.
e.g. ***templates > layout > base.html***
:::

Here are common BigCommerce configuration values. Please adjust as needed to fit your specific theme.

- **Landing Page: '/search.php'**
  This is the URL that we will send customers to when they use your search bar to access the full search results.
- **queryParam: 'search\_query'**
  This is the URL parameter used by the SRLP to fetch the search results.
- **Search URL: 'https\://eucsXXXv2.ksearchnet.com/cs/v2/search'**
  This is your Klevu APIv2 Cloud Search URL + endpoint path. You can find the base domain from Shop Info within your Klevu Merchant Center.
- **Search Box Selector: '#search\_query'**
  This is the class or ID to locate your BigCommerce theme’s input search box. You may need to change this depending on your theme.
- **Api Key: 'klevu-XXXXXXXXXXXXX'**
  This is your public Klevu JS API Key. You can find this from Shop Info within your Klevu Merchant Center.

See : [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu)  section for more detail on these elements.



### QuickSearch

Ensure the `klevu.interactive : options` value for `searchBoxSelector` matches the handle used by the HTML search \<input> field(s) within your theme.&#x20;

See :  [Quickstart : Smart Search](docId\:AMGa2LZ3adsU1tVJxhg1K)  for more details on incorporating quicksearch



### Search Result Landing Page

Next, update the SRLP to use Klevu Template JS instead of native search results.&#x20;

Within your theme editor open ***templates > pages > search.html**.*

**Option 1 :** Replace the entire contents of the file with the Klevu landing grid

e.g.

:::BlockQuote
\{\{#partial "page"}}
\<section class="page">
&#x20;   \<div class="klevuLanding">\</div>
\</section>
\{\{/partial}}
\{\{> layout/base}}
:::

**Option 2 :** Keep any page components you need by placing the `klevuLanding` target div where the search results are to be displayed.

:::BlockQuote
\<div class="klevuLanding">\</div>
:::



### Category Landing page

This section is only applicable if you have opted for the Klevu add-on to also power your BigCommerce Category Pages.

Within your theme editor open ***templates > pages > category.html***.

**Option 1 :** Replace the entire contents of the file with the Klevu landing grid

e.g.

:::BlockQuote
\{\{#partial "page"}}
\<section class="page">
&#x20;   \<div class="klevuLanding">\</div>
\</section>
\{\{/partial}}
\{\{> layout/base}}
:::

**Option 2 :** Keep any page components you need by placing the `klevuLanding` target div where the product listing results are to be displayed.

:::BlockQuote
\<div class="klevuLanding">\</div>
:::



### Recommendations

Klevu Smart Recommendations integration options are covered in the Kowledgebase guide: [Smart Recommendations Integration Guide for BigCommerce](https://help.klevu.com/support/solutions/articles/5000871324-integration-steps-for-bigcommerce)

[title] Multi-Currency
[path] How To/



To accommodat&#x65;***&#x20;additional currency pricing***, we will introduce an additional parameter to every API request.

- priceFieldSuffix

See: Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for details on preparing for Klevu JS overriding

See :  Klevu API Documentation for [Customer Groups](https://docs.klevu.com/apis/smart-search-examples#GI08Z)

# Indexing

:::hint{type="success"}
The additional currency pricing data must be supplied at the product level during catalog indexing.
:::



### XML FEED examples

Below is a [FEED XML](https://github.com/klevu/feed/blob/8030b070f2b7d707791e65a2b22b2223d2c421cd/sample.xml#L190) example for **product additional currencies**

```xml
<item>
. . .
        <price>123.45 GBP</price>
        <sale_price>100 GBP</sale_price>
        
        <additional_currencies>
            <additional_currency>
                <price>151.84 USD</price>
                <sale_price>123.00 USD</sale_price>
            </additional_currency>
            
            <additional_currency>
                <price>15240 JPY</price>
                <sale_price>12345 JPY</sale_price>
            </additional_currency>
        </additional_currencies>
        
. . .
```



Below is a [FEED XML](https://github.com/klevu/feed/blob/8030b070f2b7d707791e65a2b22b2223d2c421cd/sample.xml#L533) example for specific **group additional currencies**

```xml
 <item>
 . . .
 
    <groups>
        <group>
            <id>vip_customer_group</id>
            
            <price>49.99 GBP</price>
            <sale_price>49.99 GBP</sale_price>

            <additional_currencies>
                <additional_currency>
                    <sale_price>61.74 USD</sale_price>
                </additional_currency>
                <additional_currency>
                    <sale_price>6171 JPY</sale_price>
                </additional_currency>
            </additional_currencies>
            
        </group>
      </groups>
. . .
```





# Template JS Override

The desired currency/prices are applied to all queries via overrides using the "all" `scope` value.

See: Modify Request [Overview](docId:_ndrEPmgAUhYltIlXkG-o) for details on preparing for Klevu JS overriding

### Example 1&#x20;

Apply the selected currency for all products

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

// the currency to be applied
    var klevu_currency = 'GBP';

   klevu.modifyRequest('all', function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, 'settings.priceFieldSuffix', klevu_currency);
      });
   });
 
</script>
```
:::

| **API Parameter** | **Description**                     | **Format**  |
| ----------------- | ----------------------------------- | ----------- |
| priceFieldSuffix  | Fetch prices in a specific currency | \{CURRENCY} |

### Example 2

Apply the selected currency for a specific customer group

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">

// the currency and group of the currently logged in customer
  var klevu_currency = 'GBP';
  var klevu_loginCustomerGroup = 'vip_customer_group';

  /* IMPORTANT FOR BIGCOMMERCE APP USERS ONLY 
   * The login groupid will need an ajustment for the delimeter
   * 
   * klevu_loginCustomerGroup = klevu_loginCustomerGroup.replace('_', '--');
   * 
   */
   
    klevu.modifyRequest('all', function(data, scope){
      klevu.each(data.request.current.recordQueries, function(key, query){
        klevu.setObjectPath(query, 'settings.priceFieldSuffix', klevu_currency + '-' + klevu_loginCustomerGroup);
      });
   });
 
 
</script>
```
:::

| **API Parameter** | **Description**                                    | **Format**             |
| ----------------- | -------------------------------------------------- | ---------------------- |
| priceFieldSuffix  | Fetch prices/currency specific to a customer group | \{CURRENCY}-\{GROUPID} |

See :  Klevu API Documentation for [Customer Groups](https://docs.klevu.com/apis/smart-search-examples#GI08Z)



### Example 3

For Klevu Smart Recommendations use the Recommendations `klevu_processRECSRecordQueries` function for the outgoing query modifications

:::CodeblockTabs
JavaScript

```javascript
<script type = "text/javascript" >
function klevu_processRECSRecordQueries(recordQueries, recsKey)
{
    var recsQuery = recordQueries[0];
    
    // Apply the selected currency for all products 
    klevu.setObjectPath(recsQuery, 'settings.priceFieldSuffix', klevu_currency);
    
    /* OPTION 2:
    // Apply the selected currency for a specific customer group 
    klevu.setObjectPath(recsQuery, 'settings.priceFieldSuffix', klevu_currency + '-' + klevu_loginCustomerGroup);
    */

}
</script>
```
:::

See :  Modify Recommendations [Overview](docId\:O03QERB3F-sY0BHba64Af) for more details

[title] Magento B2B MSI
[path] How To/



The current version of Klevu’s Magento extension does not natively support indexing of Magento's Multi Source Inventory ([Inventory Management](https://developer.adobe.com/commerce/webapi/rest/inventory/)) values. The values must be provided into the Klevu index so that they may be used for constraining the results to the desired source availability and/or indicating inventory.

Two parameters are required at the product level during indexing:

1. One to identify the item is sold at the selected location
2. One to identify the item is in stock at the selected location

On the website front-end, a filter is applied “behind the scenes” to the outgoing search query to constrain results to the visitors selected source/store.

:::hint{type="info"}
If you are looking for MSI **Salable** **Availability** (true/false) only, please review our sub module add-on to see if it useful for your scenario. [https://github.com/klevu/msi](https://github.com/klevu/msi)
:::



The solution below will explain:

1] Options to provide the availability data and stock status at the product level to the Klevu Index:

- Extend the Klevu Search Module
- Klevu Feed XML
- Klevu Indexing API

2] Options to modify the outgoing search query to filter by the selected source and/or stock status:

- Klevu Search API
- Template JS V2 override
- Template JS V1 variable

:::hint{type="info"}
If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact [Customer Support ](https://help.klevu.com/support/tickets/new)for guidance specific to your version.
:::



The option selected for Indexing and Query will apply globally. It is recommended to NOT mix Indexing methods.

**Note:** the methods for obtaining the availability data will be the responsibility of your development team.

Once the *availability* values have been indexed, the outgoing search queries to Klevu can use the values for filtering based on source and/or stock availability. 

**Note:** the name and value pairs used in this document are for examples only. The actual values can be whatever best fits the implementation and business requirements so long as they are consistent.

For Example:

::Image[]{src="https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/MZRMaGvGuBa94o6iAAos5_image.png" size="82" width="1009" height="465" caption="Example variable naming" position="center" showCaption="true"}





## Indexing

Options to provide the availability data and stock status at the product level to the Klevu Index:

- Extend the Klevu Search Module
- Klevu Feed XML
- Klevu Indexing API



### Option 1: Extend the Klevu Search Module

Extend Klevu's Magento module to include the availability datapoints at the product level during catalog indexing.

The Klevu module contains a [function designed for adding additional datapoints](https://github.com/klevu/productsearch/blob/379fea472dbf1fa4eb15c3bcbf943fcb953fb89b/Model/Product/LoadAttribute.php#L295). This function can be extended as **preference** and used for additional parameters added at the product level during indexing.

`vendor/klevu/module-productsearch/Model/Product/LoadAttribute.php -> processProductAfter()`

```php
  /**
     * Process product data if want to add any extra information from third party module
     * @param $product
     * @param $parent
     * @param $item
     * @return $this|mixed
   */

    public function processProductAfter(&$product ,&$parent,&$item){
       return $this;
    }
```

**Source reference : &#x20;**[Klevu productsearch on github](https://github.com/klevu/productsearch/blob/379fea472dbf1fa4eb15c3bcbf943fcb953fb89b/Model/Product/LoadAttribute.php#L295)&#x20;

****

**Example extended class and logic:**

Because there are many ways to work within the Magento framework, the actual implementation as well as methods and applied logic for the availability data will be the responsibility of your development team.

:::hint{type="warning"}
It is strongly recommended to properly extend the Klevu extension for this purpose to avoid potential conflicts during future updates to the system.
:::

1] Extend the `LoadAttribute` class as **preference.**

```xml
<preference for="Klevu\Search\Model\Product\LoadAttribute"
            type="Klevu\Override\Model\Product\LoadAttributeCustom"/>
```

2] Override the `processProductAfter` function within the `LoadAttribute` class.

This example adds *source\_availability* and *source\_instock* as facets to the Klevu module's Indexing API call to Klevu. The product is sold at **Location1** and **Location2&#x20;**(comma separated Array), but is only in stock at **Location1**.

```php
class LoadAttributeCustom extends \Klevu\Search\Model\Product\LoadAttribute
{

     public function processProductAfter(&$product ,&$parent,&$item)
     {

         if (GET SOURCE DATA) {
     
              $product["other"]["source_availability"] = ["Location1","Location2"];
              
              if (SOURCE STOCK LOGIC HERE) {
                  $product["other"]["source_instock"] = "Location1";
              }
         
              return $this;
         }
    }

}
```

**API reference :&#x20;**[Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db)&#x20;

****

### Option 2: Klevu Feed XML

You may disengage the Klevu module's built-in sync and provide an external [XML feed](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) file with the full catalog data, including the additional Availability datapoints.

Please reference the [Knowledge Base article](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) for more information on using XML for data indexing.

The source availability datapoints can be entered using the `<attribute>` node.

In this example the product is sold at **Location1** and **Location2**, but is only in stock at **Location1**.  

```xml
 . . .
 <attributes>
  . . .
  <attribute>
      <id>source_availability</id>
      <name>Source Availability</name>
      <is_facet>true</is_facet>
      <values>
          <value>Location1</value>
          <value>Location2</value>
      </values>
  </attribute>
  <attribute>
      <id>source_instock</id>
      <name>Source InStock</name>
      <is_facet>true</is_facet>
      <values>
          <value>Location1</value>
      </values>
  </attribute>
  . . .
</attributes>
. . .
```

**Note:&#x20;**\<is\_facet> is set to *true* to allow filtering on the attribute. 

**Source References :**  [Klevu Feed Format Guide](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) and [Klevu Feed Example XML](https://github.com/klevu/feed/blob/dce928eb1c97115cc0bfbba7500d5241751d5ce4/sample.xml#L347)



### Option 3: Klevu Indexing API

You may disengage the Klevu module's built-in sync and use Klevu’s [Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db) directly for indexing the full catalog data, including the additional Availability datapoints.

The source availability datapoints can be sent using the `other` key\:value pair (as facets)

In this example the product is sold at **Location1** and **Location2**, but is only in stock at **Location1**.  

```xml
<?xml version="1.0" encoding="UTF-8" ?>
<request>
<sessionId>Your-Session-ID</sessionId>
  <records>
    <record>
      <pairs>
        <pair>
         <key>other</key>
         <value>source_availability:source_availability:Location1,Location2;source_instock,source_instock,Location1</value>
        </pair>
    . . .
    
```

**API reference :&#x20;**[Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db)&#x20;



## Querying

Options to modify the outgoing search query to filter by the selected source and/or stock status:

- Klevu Search API
- Template JS V2 override
- Template JS V1 (Legacy)

:::hint{type="info"}
If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact [Customer Support](https://help.klevu.com/support/tickets/new) for guidance specific to your version.
:::



### Option 1: Klevu Search API

Using the API parameter `customANDQuery`, a constraint can be applied for the query to those items that correspond to the selected *source\_availability* value.

**Example API request JSON using&#x20;*****customANDQuery*****&#x20;constraint**

This example adds *source\_availability* and *source\_instock* as filters to the Template JS API call to Klevu. The web visitor has selected to see items sold at **Location1** and only in stock at **Location1**.

```json
  "recordQueries": [
    {
      "settings": {
         "id": "productSearch",
        "customANDQuery": "(source_availability:\"Location1\") AND source_instock:\"Location1\")",
         . . .
    }
  ]
```

**Source Reference :**&#x20;



### Option 2: Template JS V2 Override

To apply the *Availability* constraint within the context of the Klevu Template JS UI the outgoing search request needs to be intercepted and modified.

See : [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu JS overriding

:::hint{type="success"}
You may also find Klevus [Example Customization Module](https://github.com/klevu/themev2-customisation-module/tree/master/Acme) on giHub useful for this scenario (and more).
:::



**Example override using&#x20;*****customANDQuery*****&#x20;constraint**

This example adds *source\_availability* and *source\_instock* as constraints to the Template JS API call to Klevu. The web visitor has selected to see items sold at **Location1** and only in stock at **Location1**.

The result set will only include items that meet these requirements.

```javascript
klevu.setObjectPath(
    data,
    "localOverrides.query.productList.settings.customANDQuery",
    "(source_availability:\"Location1\") AND (source_instock:\"Location1\")"
);
```

**Note:** The above example applies the constraint to `productList` query only. For a complete Javascript example of applying this to all query, see the Complete Template JS Example below.



**Complete Template JS Example**

This example uses a common function to apply the availability constraint via `customANDQuery` override for all queries on Quicksearch, Search Landing, and Category pages.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">
klevu.modifyRequest("landing,catnav", function(data, scope){
    
  // loop through all the pending queries
  klevu.each(data.request.current.recordQueries,function(key, query){ 

      // SET query contraints by availability location/stock
      klevu.setObjectPath(data,
         "localOverrides.query." + query.id + ".settings.customANDQuery",
         "(source_availability:\"Location1\") AND (source_instock:\"Location1\")"
       );

  });

});
</script>
```
:::



### Option 3: Template JS V1 (Legacy)

Klevus legacy template provides a basic means to apply preset filters via a JavaScript variable.

This example adds *source\_availability* and *source\_instock* as filters to the Template JS API call to Klevu. The web visitor has selected to see items sold at **Location1** and only in stock at **Location1**.

```javascript
var klevu_userFilterResults = "source_availability:Location1;;source_instock:Location1";
```


[title] Shopify : Use Native Product Card
[path] How To/

This guide outlines the integration of Shopify's card-product.liquid template into Klevu Search, Category Merchandising, and Recommendations. One of the use cases is to accurately display B2B prices within these features.

The concept is simple; Use a placeholder within the Klevu result [Template JS](https://docs.klevu.com/template-js) and populate it with the markup from the native card-product.liquid file within the Shopify theme.

:::hint{type="info"}
The following example is for guidance only, you will want to adapt the code as necessary to fit your theme and strategy, but it is based on the Dawn Theme.
:::



# Create a new product liquid file within Templates for this use.

This is a common step for Klevu Search, Category Merchandising, and Recommendations. The name of the file will be used in the Klevu result rendering function to fetch the card-product.liquid template via the use of Shopify’s ability to [render alternate templates](https://shopify.dev/docs/themes/architecture/templates#render-an-alternate-template) via a URL parameter. Specifically, Shopify allows you to call a product’s URL with a different template other than the one that is assigned to it. For example, a product might have the default product template assigned to it, but we want to use this new template we will create one instead. So within Edit Code and the list of Templates, let's create a new Template by clicking **add a new template**. Choose **product** from the Template Type dropdown, select **Liquid**, and let’s call this new template **klevu-template**. This will create a new template for us to use.


![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/Ig5CIzhUT4M3BbzySSB6y_image.png)

In this file, we are simply referencing the current *card-product-card* liquid file
e.g.

```javascript
{% comment %}
Klevu added for template fetch
{% endcomment %}

{%- layout none -%}

{% render 'card-product', card_product: product %}
      
```

:::hint{type="warning"}
Use ***layout none*** to omit extraneous template data and keep it to the product card markup only.
:::

:::hint{type="success"}
You will want to adhere to your **current theme’s card-product template name as well as any required data objects to be passed** (e.g. for showing the secondary image you will pass show\_secondary\_image: true).
:::

Once this action is completed, below are further steps based on the solution you want to implement.

# Klevu Search & Category Merchandising

Below are the steps to implement the product native tile on Search & Category Merchandising:

## Create the override script file within Snippets.

Similar to the instructions described above when creating a template, this time we will go to the Snippets section and click **add new snippet** to create the snippet. The name of the file will be used to include the script in the core Klevu flow where necessary

e.g.

:::BlockQuote
Snippets > **klevu-customizations**.liquid
:::

There are five elements to this file:

- Include the default card-product CSS from the Dawn theme
- *setTemplate* override to assign our new productBlock placeholder
- *afterTemplateRender* to fetch the data from the new **product.klevu-template.liquid** created above
- *template/klevu* script block for the new productBlock placeholder
- *\<style>* block for any fine-tuning based on your current theme CSS

Please reference the comments in the code example below for details on the functional steps.

:::hint{type="danger"}
The following example is for guidance only, you will want to adapt the code as necessary to fit your theme and strategy.
:::

e.g.

```javascript
{% comment %}
  Klevu added for template fetch
{% endcomment %}

<!-- We need to include the default product card styles -->
{{ 'component-card.css' | asset_url | stylesheet_tag }}

<!-- trigger the action after template render -->
<script>
  /* Assign new templates to Klevu Options (for automated integration) */
  if (typeof klevuSettings === 'undefined') {
    var klevuSettings = {};
  }
  klevuSettings.theme ??= {};
  klevuSettings.theme.setTemplates ??= {};
  klevuSettings.theme.setTemplates.myCustomProductBlock = {
    selector: '#myCustom_klevuLandingTemplateProductBlock',
    scope: 'landing,catnav',
    name: 'productBlock'
  }
</script>

<script type="text/javascript">
/* Assign new templates to Klevu Options (uncomment for manual integration)
klevu({
	theme: {
		setTemplates: {
            myCustomProductBlock: {
				scope: 'landing,catnav', // impacted scope
				selector: '#myCustom_klevuLandingTemplateProductBlock', // new markup block ID
				name: 'productBlock' // template placement name
			}
		}
	}
}); */
</script>

<!-- trigger the action after template render -->
<script>
    document.addEventListener('DOMContentLoaded', function () {
    
      klevu.afterTemplateRender('landing,catnav', async function (data, scope) {
        try {

            /* GET all the product IDs in the response */
            var productIds = data.template.query.productList.result;

            /* LOOP through the IDs */
            await Promise.all(productIds.map(async (prod) => {
                try {

                    /* FETCH the product template from Shopify API */
                    var res = await fetch(prod.url + '?view=klevu-template&variant=' + prod.id);
                    var templateBlock = await res.text();

                    /* INSERT the template markup into the placeholder */
                    var productCardHolder = document.querySelector('[data-id="' + prod.id + '"] div.kuProdWrapHolder');
                    if (res.ok) {
                        productCardHolder.innerHTML = templateBlock;
                    } else {
                        productCardHolder.remove();
                    }
                } catch (err) {
                    console.log('Not able to process this product because:', err, prod);
                }
            }));

            document.querySelectorAll('.klevuLanding .div.kuResults ul li.klevuProduct').forEach(e => {
                if (!e.textContent.trim() && e.hasChildNodes()) {
                    e.remove();
                }
            });

        } catch (err) {
            /* If we have any issues processing the above code let's log the error */
            console.log('Not able to process this product because:' + err, prod);
        }
      });
   });
</script>

<!-- productBlock override with placeholder -->
<script type="template/klevu" id="myCustom_klevuLandingTemplateProductBlock">
    <li ku-product-block class="klevuProduct klevuProductClick kuTrackRecentView grid__item" data-id="<%=dataLocal.id%>">
        <div class="kuProdWrapHolder">
          <!-- INSERT HERE product.klevu-template.liquid for <%=dataLocal.id%>  -->
        </div>
    </li>
</script>

<!-- adjust for styling as needed -->
<style>
  .kuSearchResultsPageContainer .kuResults ul li {
    width: 25%;
    padding: 0px;
    float: none;
  }
</style>
```

## Include the script file into the Klevu core flow.

This may vary depending on how you have integrated Klevu. We would recommend to put file in **Layout > theme.liquid&#x20;**&#x62;efore head closing tag.

Place the render include below the Klevu core and configurations section

e.g.

```javascript
<!-- theme.liquid code before head closing tag -->
{% render 'klevu-customizations' %}
  </head>
```

#

# Klevu Recommendations

Below are the steps to implement the product native tile on Klevu Recommendations:

## Create a new template for the Recommendations in the KMC.

To create a new template in the KMC you will need to go to Recommendations > Templates and click ‘New Template’.

To show the products using the same look & feel as the current Shopify theme we need to create a new template that has the same fundamental elements from the existing template. This may mean that a lot of the elements from the existing related products or featured products liquid templates will need to be taken. Whilst we are aiming to achieve the same look & feel of the existing template we also want to make sure we are capturing the necessary analytics using the Klevu classes from the original template.

:::hint{type="danger"}
The following example is for guidance only, you will want to adapt the code as necessary to fit your theme and strategy.
:::

```javascript
<% var metadata = data.metadata; var logic = (metadata.logic) ? metadata.logic : ""; var pageType = (metadata.pageType) ? metadata.pageType : ""; var recsKey = (metadata.recsKey) ? metadata.recsKey : ""; var title = (metadata.title) ? metadata.title : ""; %>
<div class="kuRECSContainer" data-logic="<%= logic %>" data-recskey="<%= recsKey %>" data-page-type="<%= pageType %>">
  <% var recommendationItemList = klevu.getObjectPath(data,"query.klevuRECSItemList.result");%>
  <% if(recommendationItemList && recommendationItemList.length) { %>
    <product-recommendations class="related-products page-width isolate">
      <h2 class="related-products__heading inline-richtext h2" title="<%= klevu.dom.helpers.escapeHTML(title) %>">
        <%= title %>
      </h2>
      <ul class="grid product-grid grid--4-col-desktop grid--2-col-tablet-down" role="list">
        <% helper.each(recommendationItemList, function(key, item){ %>
          <li class="grid__item">
            <div class="kuRECS-itemWrap kuRECSItem kuRECS-item" data-id="<%= item.id %>">
            </div>
          </li>
        <% }); %>
      </ul>
    </product-recommendations>
  <% } %>
</div>
```

In the above example you can see:

- We have kept the fundamental Klevu functionality to get the correct page.
- We have kept the fundamental Klevu functionality to get the recommendations list.
- We have kept the fundamental Klevu classes for the elements to make sure we are tracking all analytical data.
- We have inputted the classes from the theme to make the recommendations have the same look & feel as those in the theme.



## Create the post-render script.

Here we are creating a script to render the product card for each of the products that are part of the recommendation block being created. We are referencing the function found [here](https://docs.klevu.com/template-js/modify-recommendations#zqxoR).

:::hint{type="danger"}
The following example is for guidance only, you will want to adapt the code as necessary to fit your theme and strategy.
:::

e.g.

```javascript
<!-- We need to include the default product card styles -->
{{ 'component-card.css' | asset_url | stylesheet_tag }}

<script>
  /* Klevu runs this function once the recommendations block has been rendered */
  function klevu_bindRECSTemplateElementEvents(templateData, recsKey) {
    /* Gets an array of the products in the recommendations block */
    var productIds = templateData.query.klevuRECSItemList.result;

    /* LOOP through the IDs */
    klevu.each(productIds, async function (pkey, prod) {

      /* FETCH the product template from Shopify API */
      var res = await fetch(prod.url + '?view=klevu-template&variant=' + prod.id);
      var templateBlock = await res.text();
      
      /* INSERT the template markup into the placeholder */
      var productCardTarget = document.querySelector('[data-recskey="' + recsKey + '"]');
      var productCardHolder = productCardTarget.querySelector('div.kuRECSItem[data-id="' + prod.id + '"]');
      if (res.ok) {
        productCardHolder.innerHTML = templateBlock;
      } else {
        productCardHolder.remove();
      }
    });
  }
</script>
```

Here you can see that we are checking for the specific recommendation product ID and inputting the code block for this product in the div related to that product.



## Drop the code into the desired template.

Once you have done this you are free to create a new recommendation block, assign the new template you have created, and get the code that is spat out as a result.

You can use this code to set up recommendations using the steps given in the section **Smart Recommendation**s of the [guide](https://help.klevu.com/support/solutions/articles/5000886912-integrating-klevu-solutions).

Another option is to handle it manually.

e.g.

```javascript
<div class="klevu-recs" id="k-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX"></div>
```

You can drop this into a custom liquid block on the page you’d like to show the recommendations e.g. the home page, product page, or category page.

:::hint{type="warning"}
You may need to make some CSS changes to the custom liquid block to show certain elements correctly.
:::



# Known Caveats

When utilizing this method, it's important to note a couple of considerations:

1. If prices differ from what was synchronized with the Klevu backend (such as in a Shopify B2B system), it may affect the functionality of the price facet and sort by options on search/category pages. It will not impact the Recommendation though.
2. The load more feature (infinite scrolling) might not be compatible with the aforementioned approach.


[title] Events
[path] Library Reference/JS Library/



## DOM Events

Execute functions when DOM is fully loaded

`klevu.ready(object or functionSource) `

When the document is in ready state `klevu.isReady` will be true

- **name**: name of the function to be executed – unique per event
- **fire**: source code of the execution

`klevu.interactive(object or functionSource) `

When the Document enters the interactive state, if possible to detect or latest when the document is ready, when DOM is in this state `klevu.isInteractive` will be true

- **name**: name of the function to be executed – unique per event
- **fire**: source code of the execution

### Example

```javascript
klevu.ready(
  function(){
    console.log("document is loaded")
  }
);
```



## Defined Events (Attach)

Bind an event handler to the JavaScript event.

`klevu.event.attach : function ( target , event , callBack , useCapture )`

- **target&#xA0;**– dom node target
- **event&#xA0;**– js event name , refer to the [MDN Event Reference list](https://developer.mozilla.org/en-US/docs/Web/Events) for support
- **callBack&#xA0;**– function to be executed when event is fired
- **useCapture&#xA0;**–  default false – A Boolean indicating whether events of this type will be dispatched to the registered listener *before* being dispatched to any EventTarget beneath it in the DOM tree.

### Example

```javascript
klevu.event.attach(
 document.getElementsByTagName("body")[0],
 "click",
 function(){
    console.log("document is loaded")
  }
);
```



## Search Events

A list of search events and functions that help the power up of the search box and landing page

These are stored as part of the `klevu.searchEvents` formatted as follows

- **box**
  - focus – responsible for preprocessing the focus event and executing the scope chain chains.events.focus
  - keyup – responsible for preprocessing the keyUp event and executing the scope chain chains.events.keyUp
  - submit  – responsible for preprocessing the submit event and executing the scope chain chains.events.submit
- **general**
  - documentClick – responsible for preprocessing the document click event and executing the global chain **documentClick**
  - documentScroll – responsible for preprocessing the document scroll event and executing the global chain **documentScroll**
- **functions**
  - bindAllExtraEvents – activates the documentClick and documentScroll  events
  - bindAllSearchBoxes – selects all predefined boxes based on the selector and clones a base box for each one, also links the events for focus,keyup and submit

We automatically add a `coreEvent` named `buildSearch` that will execute when 

- the document is in interactive state
- the base search instance is build

This event will execute the 

- bindAllSearchBoxes
- bindAllExtraEvents



## Core Events

Core events are custom build and executed events.

The event will generate a klevuChain there is no data or scope on the created chain. The chain will execute from the time of creation for  **maxCount** times with an interval of **delay&#xA0;**&#x6F;r until the event evaluates to true via the **fire&#xA0;**&#x66;unction.

If the event has already executed any promise or attachment will be fired immediately.

### Interfaces

- **build&#xA0;**: function ( object ) – used to build a core event and define its functionality
- **fire&#xA0;**: function ( name ) – check if event chain can be executed and if yes execute it, stop the internal checking
- **attach&#xA0;**: function ( name , object ) – attach a function to event chain
  - name is the name of the even declared when building the event
  - object contains :
    - name: name of the function to be executed – unique per event
    - fire : source code of the execution
  - A function can be sent instead of the object
- **promise&#xA0;**: function ( name , object ) – promise function to event chain , same as attach

### Elements

A coreEvent element has the following possible parameters:

- **name&#xA0;**– event name, must be unique and will be used as reference in the attachments. building a already defined event will override fire function and can lead to unforeseen situations.
- **delay&#xA0;**– used to reference the delay between checks in ms. Default 0 ms
- **maxCount&#xA0;**– maximum number of repetitions until the event is abandoned. Default 100
- **fire&#xA0;**– function source that returns true/false , will be used to check when event chain will fire

### &#xA;Example

```javascript
klevu.coreEvent.build({
    name : "testKlevuEvent",
    fire: function(){
        if ( !klevu.isReady) {
            return false;
        } 
        return true; 
    },
    maxCount: 500,
    delay:30
  });

klevu.coreEvent.attach("testKlevuEvent",
  function(){
    console.log("Klevu is ready");
  }
);
```






[title] Examples
[path] Build UI/Modify Recommendations/

# Modify Recommendations&#x20;

Below are some common uses of modifying the Klevu Smart Recommendations data objects.&#x20;

Please review : The Modify Recommendations [Overview](docId\:O03QERB3F-sY0BHba64Af) for complete details and options.



## Modify Recommendations API Request

The below snippet contains a few examples of API query modifications using the Recommendations webhook

:::CodeblockTabs
JavaScript

```javascript
<script type = "text/javascript" >
function klevu_processRECSRecordQueries(recordQueries, recsKey)
{
    var recsQuery = recordQueries[0];

    // eg. change the result limit to 10
    klevu.setObjectPath(recsQuery, "settings.limit", 10);

    // eg. add a category context of "Clothing"
    klevu.setObjectPath(recsQuery, "settings.query.categoryPath", "Your Category");

    // eg. exclude some results for a specific banner only
    if (recsKey == 'abc-123-xyz-321') {
        var excludeIds = [
            {
              key: "id", // or itemGroupId
              value: "the-id-to-exclude"
            }
        ];
        klevu.setObjectPath(recsQuery, "settings.excludeIds", excludeIds);
    }

    // Klevu Recommendations utilise Klevu API,
    // you can therefore modify any of the params in our Docs.
    // See https://developers.klevu.com/api for all available parameters!
}
</script>
```
:::



## Modify Recommendations Template Object

The below example changes the configured `title` for a specific Recommendation banner

```javascript
function klevu_processRECSTemplateData(templateData, recsKey) {
        
    /* apply only to the specified recsKey <id> */
    if (recsKey ==  'abc-123-xyz-321') {
                
        /* replace the title as desired */
        templateData.metadata.title = 'Just For You!';
  
    }
}
```

}

[title] JS Library
[path] Library Reference/

## Overview

### Build

Events are defined using `build`. Each event will execute from the time of creation for `maxCount` times with an interval of `delay` or until the event evaluates to true via the `fire` function. This allows us to check that everything is ready before triggering the rest of our functionality, via event listeners or observers.

```javascript
klevu.coreEvent.build({
    name: "klevuExampleEvent",
    fire: function () {
        if (
            klevu.isUndefined(klevu.search.extraSearchBox)
            || (klevu.search.extraSearchBox.length == 0)
        ) {
            return false;
        } else {
            return true;
        }
    },
    maxCount: 500,
    delay: 30
});
```

When the conditions of this event have been satisfied any listeners ***attached*** to this event will fire.&#x20;



### Attach

For example, the following event listener associates an HTML template with the search box, `klevuAutoSuggestTarget`.&#x20;

Note that is is attached to the event defined as `klevuExampleEvent`

```javascript
klevu.coreEvent.attach("klevuExampleEvent", {
    fire: function () {
        klevu.each(klevu.search.extraSearchBox, function (key, box) {
            box.getScope().template.setTemplate(klevu.dom.helpers.getHTML("#KlevuTemplateAutoSuggestion"), "klevuAutoSuggestTarget", true);
        });
    }
});
```



### Chains

Another event listener will perform the more interesting parts, which is where we introduce the concept of `chains` in Klevu JavaScript Library to:

- specify some data to retrieve during the Klevu API request.
- specify what to do with that data when the response comes back.

For example, the below is an addition to the API `request.build` chain to include autosuggestions (with a count of 5) in the query response.

```javascript
box.getScope().chains.request.build.add({
    fire: function (data, scope) {
        var parameterMap = klevu.getSetting(scope.kScope.settings, "settings.search.map", false);
        var suggestion = klevu.extend(true, {}, parameterMap.suggestions);

        suggestion.id = "autosuggestion";
        suggestion.query = data.context.term;
        suggestion.typeOfRequest = "AUTO_SUGGESTIONS";
        suggestion.limit = 5; 

        data.request.current.suggestions.push(suggestion);
        data.context.doSearch = true;
    }
});
```

The next example adds to the `template.render` chain, to populate the page with our `klevuAutoSuggestTarget` template when the result contains autosuggestion data.

```javascript
box.getScope().chains.template.render.add({
    fire: function (data, scope) {
        if (data.context.isSuccess) {
            scope.kScope.template.setData(data.template);
            var targetBox = "klevuAutoSuggestTarget";
            var element = scope.kScope.template.convertTemplate(scope.kScope.template.render(targetBox));
            var target = klevu.getSetting(scope.kScope.settings, "settings.search.searchBoxTarget");
            target.innerHTML = '';
            
            scope.kScope.element.kData = data.template;
            scope.kScope.template.insertTemplate(target, element);
        }
    }
});
```



## Library Example

Putting all of the above concepts together, we have a simple HTML search box which will produce auto-suggestion terms, products, categories and CMS via the Klevu API when typing. We recommend doing this with the network tab open so you can see the API requests and responses.

***Try it yourself by clicking here:&#xA0;***[https://jsfiddle.net/klevu/dhy8t6s0/29](https://jsfiddle.net/klevu/dhy8t6s0/29)****


[title] Ratings / Reviews
[path] How To/



This guide will cover the options for Rating/Review indexing as well as where to locate the elements necessary for display customization within Template JS

 Ratings and Review data can can be used by Klevu to:

- Display Rating “stars” and Review “count” in the result set display
- Allow the visitor to refine/filter results by the number of Rating “stars”&#x20;
- Allow the visitor to SortBy Rating “stars”
- Enable Klevu Machine Learning to consider the Ratings in relevancy ranking

See : This [Knowledge Base Guide](https://help.klevu.com/support/solutions/articles/5000874210-display-product-rating---count-and-considering-it-in-klevu-ai) on how to enable each of the above. &#x20;

 

In order to allow Klevu the Rating and Review count data must first be indexed to Klevu in one of the following ways:

- Within the Feed XML file
- Within the Klevu Indexing API
- Using one of the supported 3rd party connectors
- Custom field mapping using one of Klevu's supported platform Apps/plugins
  - Please [contact Klevu support](https://help.klevu.com/support/tickets/new)  for further details on this option



# Indexing

The **Rating** and **Review Count** data must be supplied at the product level during catalog indexing.

### XML FEED example

```xml
    <item>
   . . .
        <rating>4.5</rating>
        <rating_count>10</rating_count>
   . . .
    </item>
```

See : XML FEED [Example for Ratings](https://github.com/klevu/feed/blob/8030b070f2b7d707791e65a2b22b2223d2c421cd/sample.xml#L233)**&#x20;&#x20;**



### API Reference

| **Indexing Attribute&#x20;** | **Description**                                            | **Format** |
| ---------------------------- | ---------------------------------------------------------- | ---------- |
| rating                       | The rating of your product, between 0 and 5.               | decimal    |
| rating\_count                | The number of ratings given by customers for your product. | integer    |

See : Klevu API Documentation for [Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db) &#x20;





# Customizing

### CSS

The “star” images used in the default Template JS layout are 2 different images. They are overlapped and displayed at a width percentage that is appropriate for the rating value of the record

- Gray Star : `https://js.klevu.com/klevu-js-v1/img-1-1/star-gray.png`
- Yellow Star : `https://js.klevu.com/klevu-js-v1/img-1-1/star-yellow.png`

The following class selectors can be overridden to consider different images or other desired effects:

```css
.kuFilterTagsContainer .klevuFacetStars {
  height: 15px;
  display: inline-block;
  vertical-align: bottom;
  background: transparent url(https://js.klevu.com/klevu-js-v1/img-1-1/star-gray.png) top left repeat-x;
  width: 65px;
}
.kuFilterTagsContainer .klevuFacetStars .klevuFacetRating {
  background: transparent url(https://js.klevu.com/klevu-js-v1/img-1-1/star-yellow.png) top left repeat-x;
  height: 15px;
}

```

See :  [Styling CSS](docId:2Evmr7ofKw87yl6atYU_6) for further details on overriding Template JS default CSS

 

### Sorting

The Template JS SortBy feature can be modified to include Rating Ascending/Descending order.

| **Sort Parameter Value**  | **Description**                                                                               |
| ------------------------- | --------------------------------------------------------------------------------------------- |
| RATING\_ASC, RATING\_DESC | Sort the results by each record's average rating, if this data has been indexed in your store |

See : [SortBy Options](docId\:ZvxP_bNEV_c7J-IBVzHKx) guide for examples of modifying Template JS default Sorting options



### Filtering

Filtering by Rating “stars” is accommodated like all Template JS facets.&#x20;

The key value pairs are as follows:


| **Description** | **key** | **value**  |
| --------------- | ------- | ---------- |
| one star        | rating  | 0 - 1.5    |
| two stars       | rating  | 1.51 - 2.5 |
| three stars     | rating  | 2.51 - 3.5 |
| four stars      | rating  | 3.51 - 4.5 |
| five stars      | rating  | 4.51 - 5.5 |

See : Klevu API Documentation for [Applying Facets](https://docs.klevu.com/apis/faceting#VliLQ)****





# Template JS Override

:::hint{type="warning"}
Be advised the calculations within the default Template JS are carefully constructed to accommodate the existing CSS and “star” graphics. Please take caution when modifying these aspects of the template(s)
:::

 

There are three default templates that can be accessed should you choose to override for Ratings customizations

- `klevuLandingProductRating`  - used for product block display
- `klevuLandingTemplateFilters`   - used for filter section
- `kuFilterTagsTemplate`   - used for active filter tags

See : [Set Template](docId:6YVX9naw6AX68WYguCOB7) for details on preparing for Klevu JS overriding

 

Within the JSON response object the Ratings are defined with a `type` value of "RATING". This value is used during template display logic to render specific elements for Ratings and Review Count.

**JSON response example**

```json
  "filters": [
 . . .
        {
            "key": "rating",
            "label": "Customer Reviews",
            "type": "RATING",
            "options": [
                {
                    "count": 28,
                    "name": "5",
                    "value": "4.51 - 5.5",
                    "selected": true
                }
            ]
        },
  . . .
```



### Template Override Example

This example overrides the `klevuLandingProductRating` template to display some custom text based on the item's `rating` value.

See : [Set Template](docId:6YVX9naw6AX68WYguCOB7) for details on preparing for Klevu JS Templates for overriding

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">
/* Assign new templates to Klevu Options */
klevu({
  theme: {
    setTemplates: {
      myCustomRatings: { // a unique name only to describe this template
        scope: "landing", // impacted scope
        selector: "#myCustom_klevuLandingProductRating", // new block ID
        name: "klevuLandingProductRating" // template placement name
      }
    }
  }
});
</script>
    
<script type="klevu/template" id="myCustom_klevuLandingProductRating">
<%  if(
      typeof dataLocal.rating != "undefined" && 
             dataLocal.rating !== "" &&
             dataLocal.rating > 0
    ) { %>""
    
// CUSTOM text based on Rating value  
<% if (dataLocal.rating >= 5) { %>
      <span class="topRated">TOP RATED!</span>
<% } %>
    
  <div class="klevu-stars-small-l2">
     <div class="klevu-rating-l2" style="width:<%=(20*Number(dataLocal.rating))%>%;"></div>
   </div>
        
  <%=helper.render('klevuLandingProductRatingCount',scope,data,dataLocal) %>
<% } %>
</script>
```
:::


[title] Overview
[path] Build UI/Modify Request/

# Modify Request

To modify a search request, the outgoing query to the indexed catalog is intercepted and any of the available [Klevu API ](https://developers.klevu.com/api) parameters are available to be inserted, or adjusted as needed.

There are two steps:

1. *Reference the API&#x20;*&#x74;o understand what parameters are available to meet the objective
2. *Attach the override* to the appropriate outgoing query (or queries)



## API Referencing

Any of the [Klevu API parameters](https://docs.klevu.com/apis/smart-search) are available to be applied as needed or otherwise to override any default values.

For example, the following snippet of an outgoing *productList* API Request assigns the value of "10" as the number of filter options to return.

:::BlockQuote
recordQueries: \[
&#x20;   \{
&#x20;     **filters**: \{
&#x20;       **filtersToReturn**: \{
&#x20;         **options**: \{
&#x20;           **limit**: **10**
&#x20;         }
&#x20;       }
&#x20;     },
&#x20;     id: "productList",
&#x20;     typeOfRequest: "SEARCH",
&#x20;     settings: \{
&#x20;       query: \{
&#x20;         term: "jackets"
&#x20;       }
&#x20;     }
&#x20;   }
&#x20; ],
:::

See : Klevu [API documentation on Retrieving Filters](https://docs.klevu.com/apis/faceting) for more details and options




## Attaching the Override

The query parameters are directly added or replaced by using the `klevu.modifyRequest` function.

:::BlockQuote
**klevu.modifyRequest**("\<scope>", "\<parameter object>", "\<parameter value>");
:::

The parameter object notation corresponds to that used in the outgoing JSON API query

For example, the following example snippet modifies the outgoing *productList* API Query by assigning the value of "20" as the number of filter options to return.

:::BlockQuote
klevu.modifyRequest("landing",
&#x20;   "**productList.filters.filtersToReturn.options.limit**",&#x20;
&#x20;   20
);
:::

Advanced `data` objects or modules can be accessed using a `callback function` as the parameter object

:::BlockQuote
klevu.modifyRequest("landing", function(data, scope)\{
&#x20;   console.log('modifyRequest data',data);
});
:::



## Determining Scope

**Note** that each `klevu.modifyRequest` function requires definition within the corresponding `scope` of the override. We will chart these below.

| Scope      | Description                                               |
| ---------- | --------------------------------------------------------- |
| all        | Applies to all scope modules                              |
| quick      | QuickSearch module                                        |
| landing    | SRLP module                                               |
| catnav     | Category module                                           |
| full\_page | Both SRLP and Category modules (same as "landing,catnav") |

:::hint{type="success"}
Multiple `klevu.modifyRequest` functions can be applied in the same or mixed scope.
:::



## Examples

Please see the Modify Request [Examples](docId\:HS9U2-i3tXfU0fhsg-AtK) section for details of common uses.





.

[title] Dictionary Engine
[path] Library Reference/JS Library/



The dictionary engine is the one used by multiple other engines to hold and retrieve data in a key/value format.

- Translation Engine<font color="#eb144c"></font>
- Currency Engine
- &#x20;Cache Engine



Available interfaces:

- **getGlobal&#xA0;**– gets the global stored elements
- **mergeToGlobal&#xA0;**– retrieves the elements from local and merges them into the global storage elements
- **overrideGlobal&#xA0;**– retrieves the elements from local and overrides them into the global storage elements
- **mergeFromGlobal&#xA0;**– retrieves the elements from storage and merges them into the local storage elements
- **setElements&#xA0;**– calls addElement for a list of elements to be added
- **getElements&#xA0;**– gets all elements
- **resetElements&#xA0;**– resets all elements(deletes local elements)
- **getElement&#xA0;**– gets one value for a given key of a element
- **addElement&#xA0;**– adds to local dictionary a element in the key value format
- **setStorage&#xA0;**– defines a storage for engine for the storage of the global elements of the dictionary

The dictionary is a key-value implementation that can retrieve a value for a specific key of string or number type. The key has to be unique within the scope of the generated dictionary. If same key is added it will override the local storage element that has that key.

The scope is defined by the name given on generation. The scope is only taken in consideration when interacting with the global storage of the dictionary , local storage per element can differ from one instance to another of a dictionary that is part of same scope.

Any local change can be pushed to the global storage via the interfaces provided. Any other instance with the same scope will need to merge those changes into there local storage as needed.

### Example

Using dictionary by setting an element to a dictionary and then retrieving it from another instance of the same dictionary:

```javascript
var testDictionary = klevu.dictionary("test");
    testDictionary.getElements(); // {}
    testDictionary.addElement("test","testing");
    testDictionary.mergeToGlobal();
    testDictionary.getGlobal(); // {test: "testing"}
    testDictionary.getElements(); // {test: "testing"}
var testNewDictionary = klevu.dictionary("test")
    testNewDictionary.getElements(); // {}
    testNewDictionary.getGlobal(); //  {test: "testing"}
    testNewDictionary.mergeFromGlobal();
    testNewDictionary.getElements(); // {test: "testing")
```



## dictionary.setStorage()

Sets the dictionary engine storage types for its global scope.

- storage – keyword for the storage used
- fallback – Boolean – optional – use cookie storage as fallback if using required storage is not supported.

Current supported storage engines are:

- **object&#x20;**- Default
- **local&#xA0;**– Uses browser local storage
- **session&#xA0;**– Uses browser session storage
- **cookies&#xA0;**– Uses browser cookies , persistent across session
- **cookiesSession&#xA0;**– Uses browser cookies , only for current session session

Setting a storage will also retrieve all data from the storage on the global scope. As a example if the global scope is empty but the dictionary data has been saved in the local storage previously:

```javascript
var testDictionary = klevu.dictionary("test");
testDictionary.getGlobal(); // {}
testDictionary.setStorage("local", true); 
testDictionary.getGlobal(); // {test: "test"}
```



## dictionary.getGlobal()

Used to retrieve the values directly from the global scope.

The values retrieved will still belong to the global scope and not will be part of the local scope. For example consider that global is \{test: “test”} :

```javascript
var testDictionary = klevu.dictionary("test");
testDictionary.getGlobal(); // {test: "test"}
testDictionary.getElements(); // {}
```



## dictionary.mergeFromGlobal()

Used to retrieve the values from the global scope and merge it over the local scope.

If a key is already present in the local scope with a different value it will be overridden by the value in the global scope.

```javascript
 // consider that global is {test: "test"}
var testDictionary = klevu.dictionary("test");
 testDictionary.getElements(); // {}
 testDictionary.addElement("test","testing");
 testDictionary.getElements(); // {test: "testing"}
 testDictionary.mergeFromGlobal();
 testDictionary.getElements(); // {test: "test"}
```



# Currency Engine

The currency engine is an implementation of the dictionary engine  refer to the dictionary docs for an in-depth view.

The map of a currency element, with defaults:

- **atEnd**: **false&#xA0;**– controls if the symbol is after the value
- **code**: “\<string>” – same as the global name
- **decimal**: “**.**” – symbol to be used in the decimal place
- **format**: “**%s%s**” – the format of the currency, can only contain 2 elements
- **grouping**: **3** – thousand decimal grouping
- **precision**: **2** – rounding on x decimal
- **string**: “\<symbol>” – the symbol to be used for the currency
- **thousand**: “**,**” – symbol to be used in the thousand place

Specific functions for the engine:

- **addCurrency&#xA0;**– used to add a single currency object – addCurrency : function ( Code , Map )
- **setCurrencies&#xA0;**– used to set a list of currencies
- **processCurrency&#xA0;**– retrieves the string of the formatted value in the selected currency code –  processCurrency : function ( code , value ) 

All of the Dictionary engine interfaces are available on the Currency engine



# Translator Engine

The translator engine is an implementation of the dictionary engine  refer to the dictionary docs for an in-depth view

The translator engine is used to group a specific language and the currency engine used in that language.

Specific functions for the engine:

- **translate&#xA0;**– used to reverse check a string from the dictionary, the original string is returned if no string matches dictionary. Accepts parameters to be used as format strings –&#x20;
  - example:` translate(“I have found %s Products”,5)` would return “I have found 5 Products”
- **getCurrencyObject&#xA0;**– retrieves the currency object for the translation object.

All of the Dictionary engine interfaces are available on the Translator engine.

### Example:

```javascript
klevu.search.landing.getScope().translator;
klevu.search.landing.getScope().template.getTranslator();
```



# Cache Engine

Stores a key-value map ,the engine keys do not have to be of string type but can be any object , similar to MAP

Any value (both objects and primitive values) may be used as either a key or a value. The engine is used to store individual query request/response.

The scope of the cache is always global and will be shared by all implementations of the cache engine.

### Methods:

- **getCache** – retrieves a value for a given key object
- **hasCache** – checks if a given key object has a value
- **setCache** – sets a key/value map to the cache engine
- **getAllCache** – get all cache objects

### Example:

```javascript
var cache = klevu.cache();
cache.setCache({request:"value"},{responce:"value"});
cache.hasCache({request:"value"}); // true
cache.getCache({request:"value"}); // {responce:"value"}
```

















.




[title] Infinite Scroll Results
[path] How To/



By default Klevu Template JS contains elements for pagination and number of records per page.

This can easily be replaced with an Infinite Scroll using the [Configuration](docId\:eL9qchgzNERsiaeg_E-Lu) option to enable the `resultInfiniteScroll` module.

:::CodeblockTabs
JavaScript

```typescript
<!-- Add the following below the klevu.js core script include -->
<script type="text/javascript">
klevu({
      theme: {
        modules: {
         resultInfiniteScroll: {
           quickSearch: {
             enable: true
           },
           searchResultsPage: {
             enable: true
           },
           categoryPage: {
             enable: true
           }
         }
       }
     }
})
</script>
```
:::

See : An in-action example and the source code on the [Klevu CodeSandbox](https://codesandbox.io/s/infinite-scroll-with-productlist-limit-set-to-36-ob9eoo)



### Disabling Automated Scroll-To-Top

The Infinite Scroll activation loads the additional records to Template JS using Ajax style response. In some website themes, the newly loaded array will shift the user to the top of the page.

The same effect can be witnessed using the Template JS default pagination if the user is in mid-page view and selects an alternate pagination value.

The following  example will disable the `scrollToTop` behavior in these instances for both *landing* and *catnav* scope.

Please see :**&#x20;&#x20;**[After Template Render](docId\:MFgw_8vqSnPinyQs19KJQ) section for details on this method of Klevu JS overriding

```typescript
<!-- Add the following below the klevu.js core script include -->
<script type="text/javascript">
klevu.afterTemplateRender("landing,catnav", function(data, scope){

    document.body.style.minHeight = '0';
    const currentDocumentHeight = document.documentElement.scrollHeight;
    document.body.style.minHeight = '${currentDocumentHeight}px';

    scope.kScope.chains.events.keyUp.remove({name: "scrollToTop"});

});
</script>
```












[title] Lighthouse/PageSpeed
[path] How To/





# Cumulative Layout Shift (CLS)

When using Klevu JS Theme layout for Search Results Landing Page or Category output, your search results are loaded into a predefined empty HTML element after the page has started rendering. This causes elements below the product list content to be pushed down the page, increasing the [Cumulative Layout Shift](https://web.dev/cls/) score for your page, and can negatively impact the overall [Web Vitals](https://web.dev/explore/learn-core-web-vitals) rating.

:::hint{type="info"}
For more about understanding Klevus impact on Lighthouse reports please see [this guide](https://help.klevu.com/support/solutions/articles/5000890888-improving-your-lighthouse-score-a-guide-for-developers) for other bet practices and considerations.
:::



The suggested modification options to balance CLS with Klevu Template JS are as follows:

1. **Specify min height** for the Search and Category Landing pages placeholder HTML block.
2. **Hide the footer and/or contents** below the Search result display until the results are loaded. Any content that shifts can be considered under this option.





## Option 1 : Load Footer after Klevu Search Results

**First, Apply CSS Styling to Hide Elements**

Add the following CSS to your site’s stylesheet, including selectors for all elements which need to be hidden on page load. If you cannot add to the stylesheet, you can alternatively add these styles to the template we will be creating in the next step.

&#x20;If you are hiding multiple elements on the same or different pages, you can include them all in the same list.

:::BlockQuote
\{selector}\:not(.klevuFinishLoading),
\{selector}\:not(.klevuFinishLoading) \{
&#x20;   display: none !important;
}
:::

For example, in most Shopify themes, the footer is identified by .shopify-section-group-footer-group or #shopify-section-footer (depending on the base theme and version used to develop your theme). So the CSS would look something like the following example:

:::BlockQuote
.shopify-section-group-footer-group\:not(.klevuFinishLoading) \{
&#x20;   display: none !important;
}
:::

This example will hide the footer as part of the default styles (therefore applying on page load) providing the element does not *also* have the class `.klevuFinishLoading`

We need to display this by default as hiding the element using JavaScript will run too late, potentially causing a flash of content where the footer is visible before being hidden. This may also count against CLS and is a poor user experience.



**Next, Add JavaScript to Bring Back Elements**

The following example will show the targeted blocks by adding a selector of `klevuFinishLoading` that will negate the `display:hide` as set in the first step above.

:::hint{type="info"}
**Note:&#x20;**&#x20;the `{selector},{selector}` placeholder values on (Line 12) and replace these with your target footer class selectors
:::

```javascript
<script>
    // 3000 is the number of milliseconds to wait for a response from Klevu before bringing back the footer automatically
    const klevuBringBackFooter = setTimeout(klevuBringBackFooterTimeout, 3000);
    function klevuBringBackFooterTimeout() {
        klevuBringBackFooterFunction();
        clearTimeout(klevuBringBackFooter);
    }
    
    function klevuBringBackFooterFunction() {
        // Add selectors of all elements to be reinstated below. These should match the hidden
        //  elements as targetted by CSS _without_ the :not() pseudo-selector
        let hideFooterElements = document.querySelectorAll("{selector},{selector}");
        let hideFooterElementIndex = 0;
        while (hideFooterElementIndex < hideFooterElements.length) {
            hideFooterElements[hideFooterElementIndex].classList.add("klevuFinishLoading");
            hideFooterElementIndex++;
        }
    }
    
    // Ensure elements are reinstated after a response from Klevu
    window._klvWebhook = window._klvWebhook || [];
    window._klvWebhook.push({
        object: "search",
        scope: "full_page",
        name: "chains.response.success",
        action: "after",
        fire: function(data, scope) {
            clearTimeout(klevuBringBackFooter);
            klevuBringBackFooterFunction();
        }
    });
    window._klvWebhook.push({
        object: "search",
        scope: "full_page",
        name: "chains.response.fail",
        action: "after",
        fire: function(data,scope) {
           clearTimeout(klevuBringBackFooter);
            klevuBringBackFooterFunction();
        }
    });
</script>
```

:::hint{type="warning"}
If you are using Smart Category Merchandising, you will also need to render this JavaScript on your collection pages.
:::

The site footer should now be hidden on page load and reinstated after Klevu returns and renders a product list.

## Option 2 : Apply a Minimum Height to the Klevu Results Element

If you do not want to hide your site footer, you can mitigate some of the impact of CLS by setting a minimum height on the HTML element into which Klevu results are injected.&#x20;

This is not the primary recommended approach, as accurately and consistently determining the size of this element is difficult due to variations in screen resolution and the number of results returned by a query.

**First, determine an appropriate minimum height** by performing a query on your website and inspecting the height of the `.klevuLanding div` *after results have loaded*. You should do this after performing a search that returns at least a full page of results in order to see the maximum height this element is likely to be.

![](https://archbee-image-uploads.s3.amazonaws.com/816_4eGYZQxALlijMlcBN/cMYEU7OLkPzU4yYUqJxe6_image.png "Determine height value of .klevuLanding div block")

**Next, add a minimum height to the element in your CSS stylesheet.** The code should look something like

:::BlockQuote
.klevuLanding \{
&#x20;   min-height: 920px;
}
:::

 You may also consider adjusting for alternate screen sizes

:::BlockQuote
/\* Smaller devices \*/
@media screen and (max-width: 480px) \{
&#x20;   .klevuLanding \{
&#x20;       min-height: 1300px;
&#x20;   }
&#x20;  &#x20;
}
:::



## Using Klevu Magento Extension

v2.8.0 and above of the Klevu Magento module provides an easy way to enter a minimum height value in pixels for Search and/or Category pages using Template JS.&#x20;

These settings can be found under **Stores > Settings > Configuration > Klevu > Search Configuration > Developer Settings > Minimum Height for Search Results Landing Page Content** and **Minimum Height for Category Page Content**; both are available to configure globally through to the store level.

:::hint{type="warning"}
This field only accepts numeric values corresponding to pixels. ie “920” rather than “920px” or “100%”.
:::


Using Klevu Shopify App
-----------------------

Klevu’s Shopify App provides configurable settings that can help you reduce layout shifts during the Template JS Category and/or Search page load, improving your CLS score.

Navigate to **Shopify Admin → Online Store → Theme → Customize → Search Page → Klevu Search Results Block**

For more detail on this setting please see the KnowledgeBase guide : [How to Improve Your Cumulative Layout Shift (CLS) Score Using Klevu’s Shopify App](https://help.klevu.com/support/solutions/articles/5000890950-how-to-improve-your-cumulative-layout-shift-cls-score-using-klevu-s-shopify-app)

[title] Compare Products on Results Page
[path] How To/

## Overview of customization

- Modify 3 Template JS templates to add compare feature:&#x20;
  - klevuTemplateLanding - Add a table to display compared products
  - filters - To display selected products to compare
  - productBlock - Add compare toggle to each product
- Add JavaScript to power the compare feature
  - Set attributes to display for compare
  - Tell Klevu to override default templates
  - Powerup code for compare feature
- Add CSS to style the compare feature

 

## Requirements

- You must have Klevu integrated in your store using Template JS
- You need the ability to modify the code in your store
- Compare feature will be added to the Search Result Landing Page and Category Pages

 

## Add Custom Template code

Add the following code anywhere on your store.&#x20;

This code only needs to be loaded on the pages where the compare feature will be present, so you may conditionally add this code only when these pages are accessed.

If you already have custom templates for **klevuTemplateLanding**, **filters**, and/or **productBlock**, we have added comments to show what code is necessary.&#x20;

```javascript
<script type="template/klevu" id="klevuLandingTemplateBaseCustom">
    <div ku-container data-container-id="ku_landing_main_container" data-container-role="main">

        <header ku-container data-container-id="ku_landing_main_header_container" data-container-role="header">
            <section ku-block data-block-id="ku_landing_main_header_sub_panel"></section>
            <section ku-block data-block-id="ku_landing_main_header_banner">
                <%=helper.render('klevuLandingPromotionBanner',scope,data,"top") %>
                <%=helper.render('klevuLandingPromotionBanner',scope,data,"bottom") %>
            </section>
            <section ku-block data-block-id="ku_landing_main_header_site_navigation"></section>
        </header>
            
        <div class="kuContainer">
            <% if(!helper.hasResults(data,"productList") && !helper.hasFilters(data,"productList")) { %>                
                <%=helper.render('noResultsFoundLanding',scope) %>
            <% } else { %>
                <%= helper.render('klevuLandingTemplateSearchBar', scope) %>   
                <%=helper.render('klevuLandingImageSearchUploadBanner',scope,data) %>             
                <%= helper.render('tab-results', scope) %>                
                <%= helper.render('results',scope) %>
            <% } %>
            <div class="kuClearBoth"></div>
        </div>
    
        <footer ku-container data-container-id="ku_landing_main_footer_container" data-container-role="footer">
            <section ku-block data-block-id="ku_landing_main_footer_sub_panel"></section>
            <section ku-block data-block-id="ku_landing_main_footer_banner">                

            </section>
        </footer>
    
    </div>
    <!-- start of compare customization -->
    <div class="klevu-compare-table" id="klevu-compare-table">
        <table class="klevu-compare-table__products">
            <div class="klevu-compare-table-header">
                <label class="toggle-differences"><input type="checkbox" id="toggleDifferences" <% if (klevu_compare_show_differences_checked) { %>checked<% } %> /><%= helper.translate("Show only differences")%></label>
                <button id="klevu-close-compare">
                    <svg style="pointer-events:none;" enable-background="new 0 0 386.667 386.667" height="15" viewBox="0 0 386.667 386.667" width="15">
                        <path d="m386.667 45.564-45.564-45.564-147.77 147.769-147.769-147.769-45.564 45.564 147.769 147.769-147.769 147.77 45.564 45.564 147.769-147.769 147.769 147.769 45.564-45.564-147.768-147.77z"/>
                    </svg>
                </button>
            </div>
            <thead>
                <tr>
                    <th class="klevu-compare-table__label"></th>
                    <th><img src="" alt=""><span></span></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="klevu-compare-table__label">Label</td>
                    <td><div class="spec" spec-title="Label"></div></td>
                </tr>
            </tbody>
        </table>
    </div>
    <!-- end of compare customization -->
</script>

<script type="template/klevu" id="klevuLandingTemplateFiltersCustom">
    <% if(data.query[dataLocal].filters.length > 0 ) { %>
        <div class="kuFilters" role="navigation" data-position="left" aria-label="Product Filters" tabindex="0">

            <!-- start of compare customization -->
            <div class="klevu-compare-widget klevu-compare-widget--klevu-hidden" id="klevu-compare-widget">
                <ul class="klevu-compare-widget__images"></ul>
                <div class="klevu-compare-widget__header">
                    <span><%= helper.translate("To compare")%><span class="klevu-compare-widget__selected-amount"></span></span>
                    <button id="klevu-compare-button" type="button" disabled><%= helper.translate("Compare")%></button>
                </div>
            </div>
            <!-- end of compare customization -->

        	<h3 class="kuFiltersTitleHeading"><%=helper.translate("Narrow by")%></h3>
            <% helper.each(data.query[dataLocal].filters,function(key,filter){ %>
                <% if(filter.type == "OPTIONS"){ %>
                    <div class="kuFilterBox klevuFilter <%=(filter.multiselect)?'kuMulticheck':''%>" data-filter="<%=filter.key%>" <% if(filter.multiselect){ %> data-singleselect="false" <% } else { %> data-singleselect="true"<% } %>>
                        <div class="kuFilterHead <%=(filter.isCollapsed) ? 'kuExpand' : 'kuCollapse'%>">
                            <% var filter_label = (filter.label=="klevu_price") ? "price" : filter.label; %>
                            <%=helper.translate(filter_label)%>
                        </div>
                        <div data-optionCount="<%= filter.options.length %>" class="kuFilterNames <%= (filter.options.length <= 5 ) ? 'kuFilterShowAll': '' %> <%=(filter.isCollapsed) ? 'kuFilterCollapse' : ''%>">
                            <ul>
                                <% helper.each(filter.options,function(key,filterOption){ %>
                                    <li <% if(filterOption.selected ==true) { %> class="kuSelected"<% } %>>
                                        <a
                                            target="_self" 
                                            href="#" 
                                            title="<%=helper.escapeHTML(filterOption.name)%>" 
                                            class="klevuFilterOption<% if(filterOption.selected ==true) { %> klevuFilterOptionActive<% } %>" 
                                            data-value="<%=helper.escapeHTML(filterOption.value)%>"
                                            data-name="<%=helper.escapeHTML(filterOption.name)%>" 
                                        >
                                            <span class="kuFilterIcon"></span>
                                            <span class="kufacet-text"><%=filterOption.name%></span>
                                            <% if(filterOption.selected ==true) { %>
                                                <span class="kuFilterCancel">X</span>
                                            <% } else { %>
                                                <span class="kuFilterTotal"><%=filterOption.count%></span>
                                            <% } %>
                                        </a>
                                    </li>
                                    
                                <%  }); %>
                            </ul>
                            <% if(filter.options.length > 5 ) { %>
                                <div class="kuShowOpt" tabindex="-1">
                                    <span class="kuFilterDot"></span><span class="kuFilterDot"></span><span class="kuFilterDot"></span>
                                </div>
                            <% } %>
                        </div>
                    </div>
                <% } else if(filter.type == "SLIDER")  { %>
                	<div class="kuFilterBox klevuFilter" data-filter="<%=filter.key%>">
                        <div class="kuFilterHead <%=(filter.isCollapsed) ? 'kuExpand' : 'kuCollapse'%>">
                        	<% var filter_label = (filter.label=="klevu_price") ? "price" : filter.label; %>
                            <%=helper.translate(filter_label)%>
                        </div>
                        <div class="kuFilterNames sliderFilterNames <%=(filter.isCollapsed) ? 'kuFilterCollapse' : ''%>">                           
  							<div class="kuPriceSlider klevuSliderFilter" data-query = "<%=dataLocal%>">
  								<div data-querykey = "<%=dataLocal%>" class="noUi-target noUi-ltr noUi-horizontal noUi-background kuSliderFilter kuPriceRangeSliderFilter<%=dataLocal%>"></div>
  							</div>
                        </div>
                    </div>
                <% } else if (filter.type == "RATING")  { %>
                    <div class="kuFilterBox klevuFilter <%=(filter.multiselect)?'kuMulticheck':''%>" data-filter="<%=filter.key%>" <% if(filter.multiselect){ %> data-singleselect="false" <% } else { %> data-singleselect="true"<% } %>>
                        <div class="kuFilterHead <%=(filter.isCollapsed) ? 'kuExpand' : 'kuCollapse'%>">
                            <%=helper.translate(filter.label)%>
                        </div>
                        <div data-optionCount="<%= filter.options.length %>" class="kuFilterNames <%= (filter.options.length <= 5 ) ? 'kuFilterShowAll': '' %> <%=(filter.isCollapsed) ? 'kuFilterCollapse' : ''%>">
                            <ul>
                                <% helper.each(filter.options,function(key,filterOption){ %>
                                    <li <% if(filterOption.selected ==true) { %> class="kuSelected"<% } %>>
                                        <a
                                            target="_self" 
                                            href="#" 
                                            title="<%=helper.escapeHTML(filterOption.name)%>" 
                                            class="klevuFilterOption<% if(filterOption.selected ==true) { %> klevuFilterOptionActive<% } %>" 
                                            data-value="<%=helper.escapeHTML(filterOption.value)%>"
                                            data-name="<%=helper.escapeHTML(filterOption.name)%>"
                                        >
                                            <span class="kuFilterIcon"></span>
                                            <span class="kufacet-text">
                                                <div class="klevuFacetStars">
                                                    <div class="klevuFacetRating" style="width:<%=(20*Number(filterOption.name))%>%;"></div>
                                                </div>
                                            </span>
                                            <% if(filterOption.selected ==true) { %>
                                                <span class="kuFilterCancel">X</span>
                                            <% } else { %>
                                                <span class="kuFilterTotal"><%=filterOption.count%></span>
                                            <% } %>
                                        </a>
                                    </li>
                                    
                                <%  }); %>
                            </ul>
                        </div>
                    </div>
                <% } else { %>
                    <!-- Other Facets -->
                <% } %>
            <% }); %>
            
            <!-- <div class="kuFiltersFooter">
            	<a target="_self" href="javascript:void(0)" class="kuBtn kuFacetsSlideOut kuMobileFilterCloseBtn" role="button" tabindex="0" area-label=""><%=helper.translate("Close")%></a>
  			</div> -->
            
            
        </div>
    <% } %>
</script>

<script type="template/klevu" id="klevuLandingTemplateProductBlockCustom">
    <% 
        var updatedProductName = dataLocal.name;
        if(klevu.search.modules.kmcInputs.base.getSkuOnPageEnableValue()) {
            if(klevu.dom.helpers.cleanUpSku(dataLocal.sku)) {
                updatedProductName += klevu.dom.helpers.cleanUpSku(dataLocal.sku);
            }
        }
    %>
    <li ku-product-block class="klevuProduct" data-id="<%=dataLocal.id%>">
        <div class="kuProdWrap">
            <header ku-block data-block-id="ku_landing_result_item_header">
                <%=helper.render('landingProductBadge', scope, data, dataLocal) %>
            </header>
            <% var desc = [dataLocal.summaryAttribute,dataLocal.packageText,dataLocal.summaryDescription].filter(function(el) { return el; }); desc = desc.join(" "); %>
            <main ku-block data-block-id="ku_landing_result_item_info">
                <div class="kuProdTop">
                    <div class="klevuImgWrap">
                        <a data-id="<%=dataLocal.id%>" href="<%=dataLocal.url%>" class="klevuProductClick kuTrackRecentView">
                            <img src="<%=dataLocal.image%>" origin="<%=dataLocal.image%>" onerror="klevu.dom.helpers.cleanUpProductImage(this)" alt="<%=updatedProductName%>" class="kuProdImg">
                            <%=helper.render('landingImageRollover', scope, data, dataLocal) %>
                        </a>                        
                    </div>
                    <!-- <div class="kuQuickView">
                        <button data-id="<%=dataLocal.id%>" class="kuBtn kuBtnLight kuQuickViewBtn" role="button" tabindex="0" area-label="">Quick view</button>
                    </div> -->
                </div>
            </main>
            <footer ku-block="" data-block-id="ku_landing_result_item_footer">
                <div class="kuProdBottom">               
                    <div class="kuName kuClippedOne"><a data-id="<%=dataLocal.id%>" href="<%=dataLocal.url%>" class="klevuProductClick kuTrackRecentView" title="<%= updatedProductName %>"><%= updatedProductName %></a></div>
                    <% if(dataLocal.inStock && dataLocal.inStock != "yes") { %>
                        <%=helper.render('landingProductStock', scope, data, dataLocal) %>              
                    <% } else { %>
                    <% if(klevu.search.modules.kmcInputs.base.getShowPrices()) { %>
                        <div class="kuPrice">
                            <%
                                var kuTotalVariants = klevu.dom.helpers.cleanUpPriceValue(dataLocal.totalVariants);
                                var kuStartPrice = klevu.dom.helpers.cleanUpPriceValue(dataLocal.startPrice,dataLocal.currency);
                                var kuSalePrice = klevu.dom.helpers.cleanUpPriceValue(dataLocal.salePrice,dataLocal.currency);
                                var kuPrice = klevu.dom.helpers.cleanUpPriceValue(dataLocal.price,dataLocal.currency);
                            %>
                            <% if(!Number.isNaN(kuTotalVariants) && !Number.isNaN(kuStartPrice)) { %>
                                <div class="kuSalePrice kuStartPrice kuClippedOne">
                                    <span class="klevuQuickPriceGreyText"><%=helper.translate("Starting at")%></span>
                                    <span><%=helper.processCurrency(dataLocal.currency,parseFloat(dataLocal.startPrice))%></span>                                
                                </div>
                            <% } else if(!Number.isNaN(kuSalePrice) && !Number.isNaN(kuPrice) && (kuPrice > kuSalePrice)){ %>
                                <span class="kuOrigPrice kuClippedOne">
                                    <%= helper.processCurrency(dataLocal.currency,parseFloat(dataLocal.price)) %>
                                </span>
                                <span class="kuSalePrice kuSpecialPrice kuClippedOne">
                                    <%=helper.processCurrency(dataLocal.currency,parseFloat(dataLocal.salePrice))%>
                                </span>
                            <% } else if(!Number.isNaN(kuSalePrice)) { %>
                                <span class="kuSalePrice kuSpecialPrice">
                                    <%= helper.processCurrency(dataLocal.currency,parseFloat(dataLocal.salePrice)) %>
                                </span>
                            <% } else if(!Number.isNaN(kuPrice)) { %>
                                <span class="kuSalePrice">
                                    <%= helper.processCurrency(dataLocal.currency,parseFloat(dataLocal.price)) %>
                                </span>
                            <% } %>
                            <%=helper.render('searchResultProductVATLabel', scope, data, dataLocal) %>
                        </div>
                    <% } %>
                    <% } %>
                </div>
                <div class="kuProdAdditional">
                    <div class="kuProdAdditionalData">
                        <% if(desc && desc.length) { %>
                            <div class="kuDesc kuClippedTwo"> <%=desc%> </div>
                        <% } %>
                        <%=helper.render('landingProductSwatch',scope,data,dataLocal) %>
                        <%=helper.render('klevuLandingProductRating',scope,data,dataLocal) %>
                        <% var isAddToCartEnabled = klevu.search.modules.kmcInputs.base.getAddToCartEnableValue(); %>
                        <% if(isAddToCartEnabled) { %>
                            <%=helper.render('landingPageProductAddToCart',scope,data,dataLocal) %> 
                        <% } %>
                    </div>
                </div>
             </footer>             
        </div>

        <!-- start of compare customization -->
        <button class="klevu-compare" data-id="<%=dataLocal.id%>" data-itemGroupId="<%=dataLocal.itemGroupId%>">
            <input id="klevuCompare_<%=dataLocal.id%>" class="klevu-compare__checkbox" type="checkbox" style="pointer-events:none"/>
            <label for="klevuCompare_<%=dataLocal.id%>" class="klevu-compare__label"> <%= helper.translate("Compare")%> </label>
        </button>
        <!-- end of compare customization -->

    </li>
</script>
```

## Add JavaScript Code

First, let’s add the code that will choose which attributes to callout when products are compared

```javascript
// Array of keys you want to render in the Compare table
window.KEYS_TO_COMPARE = [
  "inStock",
  "grams",
  "sku",
  "brand",
  "size",
  "category"
  // "tags",
  // "type",
  // "itemGroupId",
  // "storeBaseCurrency",
  // "inventory_item_id",
  // "imageUrl",
  // "currency",
  // "id",
  // "image",
  // "url",
  // "product_type",
  // "name",
  // "shortDesc",
];
```

Next we need to tell Klevu to use our custom templates. Skip this step if you are already customizing all three of these templates (**klevuTemplateLanding**, **filters**, and **productBlock)**. You may need to modify the code if you only have one or two of these templates.

```javascript
klevu({
  theme: {
    setTemplates: {
      compareBase: {
        scope: "landing,catnav",
        selector: "#klevuLandingTemplateBaseCustom",
        name: "klevuTemplateLanding"
      },
      compareFilters: {
        scope: "landing,catnav",
        selector: "#klevuLandingTemplateFiltersCustom",
        name: "filters"
      },
      compareProductBlock: {
        scope: "landing,catnav",
        selector: "#klevuLandingTemplateProductBlockCustom",
        name: "productBlock"
      }
    }
  }
});
```

Now we need to add the code that will powerup the compare feature:&#x20;

```javascript
// This settings controls whether to Show only differences on page load or not.
window.klevu_compare_show_differences_checked = true;

klevu.afterTemplateRender('landing,catnav', function(data, scope){
     /** COMPARE PRODUCTS FEATURE */
  const docBody = document.getElementsByTagName('body')[0];
  const klevuAPIkey = klevu.getGlobalSetting("search.apiKey", klevu.getGlobalSetting("global.apiKey"));
  const placeholderImageUrl = 'https://js.klevu.com/klevu-js-v1/img-1-1/place-holder.jpg'; // Replace with your placeholder image URL
  const klevuScope = klevu.getSetting(klevu, "settings.flags.setRemoteConfigLanding.build") ? 'landing' : 'catnav';

  toggleCheckbox();
  saveCompareDataToLocalStorage();
  [...document.querySelectorAll('.klevu-compare')].forEach(element => {
    klevu.event.attach(element, "click", clickHandler_addToCompareList);
  });

  docBody.addEventListener('click', function ({ target }) {
    try {
      if (target.matches('#klevu-compare-button, #klevu-compare-button *, #klevu-compare-table, #klevu-compare-table *')) {
        docBody.classList.add('klevu-compare-table-shown');
      } else {
        docBody.classList.remove('klevu-compare-table-shown');
      }
      // close button
      if (target.matches("#klevu-close-compare, #klevu-close-compare *")) {
        docBody.classList.remove('klevu-compare-table-shown');
      }
    } catch (err) { }
  })

  function getKlevuCompareIdArray() {
    return localStorage.getItem(`klevu-compare-ids-${klevuScope}-${klevuAPIkey}`) ? JSON.parse(localStorage.getItem(`klevu-compare-ids-${klevuScope}-${klevuAPIkey}`)) : [];
  }

  function saveIDsToLocalStorage(currID, forceOverride = false) {
    if (forceOverride) {
      // Save the updated data back to local storage
      localStorage.setItem(`klevu-compare-ids-${klevuScope}-${klevuAPIkey}`, JSON.stringify(currID));
    } else {
      let existingIDs = getKlevuCompareIdArray();

      if (!getKlevuCompareIdArray().includes(currID)) { // Check if the ID is not already in the existing data
        existingIDs.push(currID); // Add the new ID to the existing data
      } else if (getKlevuCompareIdArray().includes(currID)) {
        const existingIndex = getKlevuCompareIdArray().indexOf(currID);
        existingIDs.splice(existingIndex, 1); // Remove this ID from the existing data
      }

      // Save the updated data back to local storage
      localStorage.setItem(`klevu-compare-ids-${klevuScope}-${klevuAPIkey}`, JSON.stringify(existingIDs));
    }
  };

  function saveCompareDataToLocalStorage(data = null) {
    localStorage.setItem(`klevu-compare-data-${klevuScope}-${klevuAPIkey}`, data);

    // If no argument passed && there are some IDs in the storage, but no entries in local storage
    if (data === null && getKlevuCompareIdArray() && !getKlevuCompareDataObject()) {
      getAndSaveDataByIDs(getKlevuCompareIdArray());
    }
  }

  function getKlevuCompareDataObject() {
    return JSON.parse(localStorage.getItem(`klevu-compare-data-${klevuScope}-${klevuAPIkey}`))
  }

  function clearImgUrl(url) { return url.replace("/needtochange/", "/") };

  function renderSideWidget() {
    const selectedProductsAmount = getKlevuCompareIdArray().length || null;
    const widgetElement = document.querySelector('#klevu-compare-widget');
    const widgetCompareButtonElement = document.querySelector('#klevu-compare-button');
    const selectedProductsAmountElement = document.querySelector('.klevu-compare-widget__selected-amount');
    const selectedProductsImagesElement = document.querySelector('.klevu-compare-widget__images');
    let widgetHTMLlistItem = '';

    getKlevuCompareDataObject().map(item => {
      const imageUrl = item.image ? clearImgUrl(item.image) : placeholderImageUrl;
      widgetHTMLlistItem += `
                    <li class="klevu-compare-widget__item">
                        <button class="klevu-compare-widget__item-button" data-id="${item.id}" title="Remove from Klevu comparison">
                            <img class="klevu-compare-widget__item-image" alt="${item.name}" style="max-height:50px;max-width:40px;" src="${imageUrl}" onerror="this.onerror=null; this.src='${placeholderImageUrl}'" />
                            <i class="klevu-compare-widget__item-button-cross">&times;</i>
                        </button>
                    </li>`;
      selectedProductsImagesElement.innerHTML = widgetHTMLlistItem;
    });


    if (selectedProductsAmount && widgetElement) {
      selectedProductsAmountElement.innerHTML = selectedProductsAmount;
      selectedProductsImagesElement.innerHTML = widgetHTMLlistItem;
      widgetElement.classList.remove('klevu-compare-widget--klevu-hidden');
      if (selectedProductsAmount > 1) {
        widgetCompareButtonElement.disabled = false;
      } else {
        widgetCompareButtonElement.disabled = true;
      }
    } else if (widgetElement) {
      widgetElement.classList.add('klevu-compare-widget--klevu-hidden');
    }

  }

  function generateAddToCartHTML(item) {
    // Check if the item is in stock
    if (item.inStock !== "no") {
      // Get the 'Add to Cart' caption
      var addToCartCaption = klevu.getObjectPath(klevu.search, "modules.kmcInputs.kmcData.klevu_uc_userOptions.addToCartButton", "Add to cart");

      var translatedCaption;
      if (typeof klevu_uc_userOptions !== 'undefined' && klevu_uc_userOptions) {
        translatedCaption = klevu_uc_userOptions.addToCartButton;
      }

      // Check if the 'Add to Cart' caption contains an image
      if (addToCartCaption) {
        return `
                    <div class="kuAddtocart" data-id="${item.id}">
                        <a target="_self" href="javascript:void(0)" class="kuBtn kuBtnDark kuLandingAddToCartBtn" role="button" tabindex="0" aria-label="Add to cart">${addToCartCaption}</a>       
                    </div>
                `;
      }
    }
    return '';
  }

  function generatePriceHTML(data) {
    var kuTotalVariants = klevu.dom.helpers.cleanUpPriceValue(data.totalVariants);
    var kuStartPrice = klevu.dom.helpers.cleanUpPriceValue(data.startPrice, data.currency);
    var kuSalePrice = klevu.dom.helpers.cleanUpPriceValue(data.salePrice, data.currency);
    var kuPrice = klevu.dom.helpers.cleanUpPriceValue(data.price, data.currency);

    var processCurrency = scope.kScope.template.getTemplateSettings().helpers.processCurrency;

    let htmlParts = [''];

    if (!isNaN(kuTotalVariants) && !isNaN(kuStartPrice)) {
      htmlParts.push(`
                <div class="kuSalePrice kuStartPrice kuClippedOne">
                    <span class="klevuQuickPriceGreyText">Starting at</span>
                    <span>${processCurrency(data.currency, parseFloat(data.startPrice))}</span>                                
                </div>`);
    } else if (!isNaN(kuSalePrice) && !isNaN(kuPrice) && (kuPrice > kuSalePrice)) {
      htmlParts.push(`
                <span class="kuOrigPrice kuClippedOne">
                    ${processCurrency(data.currency, parseFloat(data.price))}
                </span>
                <span class="kuSalePrice kuSpecialPrice kuClippedOne">
                    ${processCurrency(data.currency, parseFloat(data.salePrice))}
                </span>`);
    } else if (!isNaN(kuSalePrice)) {
      htmlParts.push(`
                <span class="kuSalePrice kuSpecialPrice">
                    ${processCurrency(data.currency, parseFloat(data.salePrice))}
                </span>`);
    } else if (!isNaN(kuPrice)) {
      htmlParts.push(`
                <span class="kuSalePrice">
                    ${processCurrency(data.currency, parseFloat(data.price))}
                </span>`);
    }

    htmlParts.push('');

    return htmlParts.join('');
  }

  function renderCompareProducts() {
    const selectedProductsAmount = getKlevuCompareIdArray().length || null;
    const tableElement = document.querySelector('#klevu-compare-table');
    const tableHeadElement = tableElement.querySelector('thead tr');
    const tableOptionElement = tableElement.querySelector('tbody');
    let listItemHeadingHTML = ``;
    let listItemOptionHTML = ``;


    getKlevuCompareDataObject().forEach(item => {
      const imageUrl = item.image ? clearImgUrl(item.image) : placeholderImageUrl;

      listItemHeadingHTML += `<th>
                <img src="${imageUrl}" alt="${item.name}">
                <div class="kuName kuClippedOne">
                    <a data-id="${item.id}" href="${item.url}" class="klevuProductClick" title="${item.name}">${item.name}</a>
                </div>
                <div class="kuPrice">${generatePriceHTML(item)}</div>
                <button class="klevu-compare-widget__item-button" data-id="${item.id}" title="Remove from Klevu comparison"><span>&times;</span></button>
                ${generateAddToCartHTML(item)}
            </th>`;
    });

    try {
    
      KEYS_TO_COMPARE.forEach(key => {
        // Map out the values for this key from each product
        const values = getKlevuCompareDataObject().map(item => item[key] || '');

        // Check if all values are the same, ignoring case
        const allValuesSame = values.every((val, _, arr) => val.toLowerCase() === arr[0].toLowerCase());

        // Determine whether to add the 'hide' class based on the comparison
        const trClass = allValuesSame && klevu_compare_show_differences_checked ? 'hide' : '';

        const valueRows = values.map(value => `<td><span class="spec" spec-title="${key}">${value}</span></td>`).join('');

        if (valueRows.trim()) { // Only add the row if it's not empty
          listItemOptionHTML += `<tr class="${trClass}" data-name="${key}"><td class="klevu-compare-table__label">${key}</td>${valueRows}</tr>`;
        }
      });
    } catch (error) {
      console.log('KEYS_TO_COMPARE array error. Please declare the KEYS_TO_COMPARE Array!', error);
    }

    tableHeadElement.innerHTML = `<th class="klevu-compare-table__label">&nbsp;</th> ${listItemHeadingHTML}`;
    tableOptionElement.innerHTML = listItemOptionHTML;

    if (selectedProductsAmount) {
      // Add code for displaying the selected products amount
    } else {
      // Add code for handling no selected products
    }
  }

  function toggleDifferences() {
    const toggleDifferencesCheckbox = document.getElementById('toggleDifferences');
    toggleDifferencesCheckbox.addEventListener('change', function () {
      const rows = document.querySelectorAll('#klevu-compare-table tbody tr');
      rows.forEach(row => {
        const values = [...row.querySelectorAll('td span.spec')].map(spec => spec.textContent.trim().toLowerCase());
        const allEqual = values.every(val => val === values[0]);
        if (allEqual) {
          row.classList.toggle('hide', this.checked);
        }
      });
    });
  }

  function renderCompareWidget() {
    renderSideWidget();
    renderCompareProducts();
    toggleDifferences();
  }

  function getAndSaveDataByIDs(idArray) {
    /** SEND REQUEST - get products by IDs */
    const idQueryString = `(${idArray.map(id => `id:"${id}"`).join(" OR ")})`;
    var data = JSON.stringify({
      recordQueries: [
        {
          settings: {
            customANDQuery: idQueryString,
            query: { term: "*" },
            typeOfRecords: ["KLEVU_PRODUCT"],
            fields: [],
            limit: idArray.length,
          },
          id: "productSearch",
        },
      ], context: { apiKeys: [klevuAPIkey] },
    });
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        const results = JSON.parse(this.responseText).queryResults[0].records;
        fireAfterRequest(results);
      }
    });
    xhr.open("POST", klevu.settings.url.search);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(data); // Send the request
  }

  function toggleCheckbox(currentId = null) {

    try {
      if (currentId) {
        // on click:
        if (getKlevuCompareIdArray().includes(currentId)) {
          document.querySelector(`.klevu-compare[data-id="${currentId}"]`).classList.add('klevu-selected');
          document.querySelector(`.klevu-compare[data-id="${currentId}"] input`).checked = true;
        } else {
          document.querySelector(`.klevu-compare[data-id="${currentId}"]`).classList.remove('klevu-selected');
          document.querySelector(`.klevu-compare[data-id="${currentId}"] input`).checked = false;
        }
      } else {
        // on load: 
        [...document.querySelectorAll('.klevu-compare')].forEach(element => {
          // if (getKlevuCompareIdArray().includes(element.dataset.itemgroupid)) {
          if (getKlevuCompareIdArray().includes(element.dataset.id)) {
            element.classList.add('klevu-selected');
            element.querySelector('input.klevu-compare__checkbox').checked = true;
          }
        });
      }
    } catch (error) {

    }

  }

  function removeFromKlevuComparison(id) {

    [...document.querySelectorAll('.klevu-compare-widget__item-button')].forEach(element => {
      element.addEventListener('click', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();

        // const currID = ev.target.closest('.klevu-compare-widget__item-button').dataset.itemgroupid;
        const currID = ev.target.closest('.klevu-compare-widget__item-button').dataset.id;
        const filteredData = getKlevuCompareIdArray().filter(val => val !== currID);
        saveIDsToLocalStorage(filteredData, true);
        getAndSaveDataByIDs(getKlevuCompareIdArray());
        toggleCheckbox(currID);

        // hide compare popup if there's 1 product
        if (getKlevuCompareIdArray().length <= 1) {
          docBody.classList.remove('klevu-compare-table-shown');
        }
      })
    });

  }

  function clickHandler_addToCompareList(event) {
    // const currentId = event.target.closest('.klevu-compare').dataset.itemgroupid;
    const currentId = event.target.closest('.klevu-compare').dataset.id;

    event.stopPropagation();
    event.preventDefault();

    saveIDsToLocalStorage(currentId);
    toggleCheckbox(currentId);
    getAndSaveDataByIDs(getKlevuCompareIdArray());
    // renderCompareWidget();
  }

  function fireAfterRequest(results) {
    saveCompareDataToLocalStorage(JSON.stringify(results));
    renderCompareWidget();
    removeFromKlevuComparison();
  }

  /** END OF COMPARE PRODUCTS FEATURE */
});
```

## Add CSS Code

The final step is to add the CSS code that will style the compare feature.&#x20;

```css
<style>
/* COMPARE FEATURE */

.kuSearchResultsPageContainer [ku-container] .klevu-compare,
.kuSearchResultsPageContainer .klevu-compare {
  display: flex;
  justify-content: center;
  align-content: center;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  background-color: #fff;
  padding: 3px 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid var(--klevu-bgcolor);
  border-radius: var(--klevu-buttonRadius);
}

.kuSearchResultsPageContainer [ku-container] #klevu-compare-button,
.kuSearchResultsPageContainer #klevu-compare-button {
  color: #fff;
  cursor: pointer;
  background-color: var(--klevu-blue);
  border: 0;
  padding: 5px 8px;
}

.kuSearchResultsPageContainer [ku-container] #klevu-compare-button:disabled,
.kuSearchResultsPageContainer #klevu-compare-button:disabled {
  cursor: no-drop;
  opacity: 0.5;
}

.kuSearchResultsPageContainer [ku-container] .klevu-compare__checkbox,
.kuSearchResultsPageContainer .klevu-compare__checkbox {
  margin: 0;
}

.kuSearchResultsPageContainer [ku-container] .klevu-compare__label,
.kuSearchResultsPageContainer .klevu-compare__label {
  margin-left: 5px;
  cursor: pointer;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__selected-amount::before {
  content: ':';
  margin-left: 0;
  margin-right: 5px;
}

.kuSearchResultsPageContainer [ku-container] div #klevu-compare-widget {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 10px auto;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__header {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__images {
  display: flex;
  align-items: center;
  gap: 0 10px;
  margin: 0;
  padding: 0;
  overflow-x: auto;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__item {
  list-style: none;
  border: 1px solid transparent;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__item:hover {
  list-style: none;
  border: 1px solid #888;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__item-button {
  border: 0;
  background-color: transparent;
  padding: 0;
  margin: 0;
  cursor: pointer;
  position: relative;
}

.kuSearchResultsPageContainer [ku-container] div .klevu-compare-widget__item-button-cross {
  position: absolute;
  font-style: normal;
  top: -5px;
  right: 0;
}

.kuSearchResultsPageContainer #klevu-close-compare {
  background-color: #fff;
  border: 0;
  padding: 15px;
  cursor: pointer;
  z-index: 1;
  border: 1px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.kuSearchResultsPageContainer #klevu-close-compare:hover {
  border: 1px solid var(--klevu-black)
}

.kuSearchResultsPageContainer #klevu-compare-table tr {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
}

.kuSearchResultsPageContainer #klevu-compare-table thead {
  position: sticky;
  top: 0;
}

.kuSearchResultsPageContainer #klevu-compare-table tr th .klevu-compare-widget__item-button {
  position: absolute;
  top: 0;
  right: 0;
  background-color: var(--klevu-blue);
  color: #fff;
  border: 0;
}

.kuSearchResultsPageContainer [ku-container] div #klevu-compare-widget.klevu-compare-widget--klevu-hidden {
  display: none;
  visibility: hidden;
}

.kuSearchResultsPageContainer .klevu-compare-table {
  display: none;
  visibility: hidden;
  background: #fff;
  max-height: calc(100vh - 10%);
  overflow: auto;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 85vw;
  z-index: 1000;
}

body.klevu-compare-table-shown .kuSearchResultsPageContainer .klevu-compare-table {
  display: block;
  visibility: visible;
}

body.klevu-compare-table-shown .kuSearchResultsPageContainer [data-container-role=main] .kuContainer {
  filter: blur(3px);
}

body.klevu-compare-table-shown .kuSearchResultsPageContainer .klevuWrap::before {
  background-color: #000;
  opacity: 0.5;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: block;
  content: '';
  z-index: 1;
}

.kuSearchResultsPageContainer .klevu-compare-table table {}

.kuSearchResultsPageContainer .klevu-compare-table th {
  position: sticky;
  /* Make th sticky to avoid JavaScript */
  z-index: 1;
  /* border: 1px solid #ccc; */
  top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.kuSearchResultsPageContainer .klevu-compare-table th:not(:last-child),
.kuSearchResultsPageContainer .klevu-compare-table td:not(:last-child) {
  border-right: 1px solid #ccc;
}

.kuSearchResultsPageContainer .klevu-compare-table td,
.kuSearchResultsPageContainer .klevu-compare-table th {
  padding: 10px;
  min-width: 300px;
  /* Add a minimum width below which no resize is allowed (for small screens). It can be whatever serves the design best */
  text-align: center;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__products {
  /* padding-top: 40px; */
  max-height: calc(100vh - 10%);
  overflow: auto;
  padding: 15px;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__products th,
.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__products td {
  width: 25%;
  max-width: 300px;
  overflow: hidden;
  gap: 10px 0;
  /* Depending on the number of products in comparison, different classes should be used (e.g. 3 products should have a .products-3 class with a width of 33.333%) */
}

.kuSearchResultsPageContainer .klevu-compare-table th {
  background: #fff;
  /* top: -2px; */
  top: 0;
  /* We need this to attach the "stuck" attribute */
}

.kuSearchResultsPageContainer .klevu-compare-table th h4 {
  margin: 15px 0 0;
}

.kuSearchResultsPageContainer .klevu-compare-table th img {
  max-height: calc(var(--klevu-product-image-height--desktop) - 50px) !important;
  max-width: 100%;
  object-fit: contain;
  margin: 0 auto;
  display: block;
  transition: height 200ms ease-in-out;
}

.kuSearchResultsPageContainer .klevu-compare-table th .kuName {
  display: block !important;
}

.kuSearchResultsPageContainer .klevu-compare-table th .kuPrice {
  margin-top: auto;
  text-align: center;
}

.kuSearchResultsPageContainer .klevu-compare-table th .kuBtn,
.kuSearchResultsPageContainer .klevu-compare-table th .kuAddtocart {
  margin: 0;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__sticky img {
  height: 100px;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__label {
  font-weight: bold;
  text-align: left;
  min-width: 150px;
  /* Labels should have a strict width, based on the design (150px is just for this demo) */
  width: 150px;
  /* In order to enforce the width we need to apply both a min-width and a width with the same value */
  background: #eee;
}

.kuSearchResultsPageContainer .klevu-compare-table th.klevu-compare-table__label {
  background: #fff;
  border-color: #fff;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__heading {
  background: #ccc;
  width: 100%;
  text-align: left;
  position: relative;
}

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__heading span {
  position: sticky;
  top: 0;
  left: 10px;
}

.kuSearchResultsPageContainer .klevu-compare-table .spec {
  word-break: break-all;
}

.kuSearchResultsPageContainer #klevu-compare-table .hide {
  display: none;
  visibility: hidden;
}

.kuSearchResultsPageContainer #klevu-compare-table .klevu-compare-table-header {
  z-index: 2;
  background-color: #fff;
  position: sticky;
  top: 0;
  right: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
}

.kuSearchResultsPageContainer #klevu-compare-table .toggle-differences {
  position: sticky;
  top: 5px;
  left: 5px;
  padding: 10px 15px;
  border: 1px solid var(--klevu-black);
}

/* @media all and (max-width: 600px) { */

.kuSearchResultsPageContainer .klevu-compare-table .klevu-compare-table__label {
  display: none;
  /* We want to hide the labels on small screens... */
}

.kuSearchResultsPageContainer .klevu-compare-table .spec::before {
  /* ...and show them above each spec instead. */
  content: attr(spec-title);
  color: #999;
  display: block;
  text-transform: capitalize;
}

/* COMPARE FEATURE END */
</style>
```

