> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# バックエンドまたはモバイルアプリで検索ロジックを実装する

> Kameleoon Product Recommendation APIを使用して、バックエンドまたはモバイルアプリケーションでライブおよびフル商品検索結果を表示します。

このガイドでは、Kameleoon HTML要素を埋め込むことなく、Product Recommendation APIにクエリを送信して、ライブ（インスタント）およびフル商品検索結果を表示する方法について説明します。ビジュアル方式については、[ビジュアル統合ガイド](/user-manual/recommendations-and-merchandising/recommendations/enable-kameleoon-search-capabilities#technical-implementation-of-kameleoon-instant-search)を参照してください。

このチュートリアルでは、**[Searchエンドポイント](../all-endpoints/Search/get-search)** を使用します。

## なぜAPIを使用するのか？

<Warning>
  モバイルアプリケーションではAPIを使用してください。
</Warning>

ニーズに応じて、このアプローチには複数の利点があります。

* **完全な制御**: デザインとUX基準に合わせてバリエーション表示をカスタマイズできます。
* **より優れたパフォーマンス**: スクリプトベースのソリューションと比較して、最適化されたAPI呼び出しによりページ読み込み遅延を低減します。
* **デバッグの容易さ**: 標準ツールを使用して、クライアントのコードベース内で統合をログ記録、監視、デバッグできます。
* **サードパーティスクリプトへの非依存**: 直接呼び出しを使用することで、外部スクリプトを回避し、潜在的な競合を減らし、セキュリティポリシーに準拠できます。
* **SPA対応**: シングルページアプリケーションに直接統合することで、タイミングの問題を回避し、クライアント側ルーティングに適合します。
* **広告ブロッカーに強い**: サードパーティスクリプトや特定のHTMLマーカーなしで、実験を一貫して配信します。広告ブロッカーがKameleoonに与える影響の詳細については、**[FAQ](../../../feature-experimentation/technical-reference/faq-global#how-do-ad-blockers-affect-kameleoon)** を参照してください。

## 目的

インスタント（タイプアヘッド）またはフル検索モードを使用して、ユーザー入力に基づいて商品検索結果を取得して表示します。

## 要件

* **Store ID (`shop_id`)** を持つ有効なKameleoonアカウント。

  * Kameleoonアプリの **Recommendations** > **Settings** > **Store settings** から `shop_id` を取得してください。必要に応じてキーについてカスタマーサクセスマネージャーにお問い合わせください。

  <Frame>
    ![Store Key](https://storage.googleapis.com/kameleoon-storage-documentation/developers/images/api-tutorial/store-key.jpg)
  </Frame>

* **Device ID (`did`)** および **Session ID (`sid`)**。（履歴的なデバイス／ユーザーデータに依存するフィルターまたはアルゴリズムを使用する場合のみ必要）。
  * **Kameleoon Web Experimentation** の場合、以下のクッキーから取得します。
    * `KameleoonProducts_device_id` → **Device ID (`did`)**
    * `KameleoonProducts_session_code` → **Session ID (`sid`)**
  * それ以外の場合は、これらの値を手動で生成してください。

## ステップ

### 1. Kameleoon検索用にフィードを構成する

[検索構成ガイド](/user-manual/recommendations-and-merchandising/recommendations/enable-kameleoon-search-capabilities)に従ってフィードを構成してください。

### 2. クッキーを取得する（Kameleoon Web Experimentationのみ）

<Warning>
  バックエンド実装やKameleoon Web Experimentationを使用しない環境では、これらの値を手動で生成してください。詳細については **[Initエンドポイント](../all-endpoints/Initialize/init)** を参照してください。
</Warning>

```javascript theme={null}
function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  if (match) return match[2];
}
const did = getCookie('KameleoonProducts_device_id');
const sid = getCookie('KameleoonProducts_session_code');
```

### 3. 検索リクエストを行う

APIは2種類の検索をサポートしています。

#### a. インスタント検索 (instant\_search)

ユーザーが入力するときのタイプアヘッドおよびオートコンプリート結果には、インスタント検索を使用します。

**エンドポイント:**

```
GET https://api.products.kameleoon.com/search
```

| 名前             | 型      | 必須    | 説明                   |
| :------------- | :----- | :---- | :------------------- |
| `did`          | string | True  | Device ID（クッキーから取得）  |
| `sid`          | string | True  | Session ID（クッキーから取得） |
| `shop_id`      | string | True  | KameleoonストアID       |
| `type`         | string | True  | `"instant_search"`   |
| `search_query` | string | True  | ユーザーの検索入力            |
| `locations`    | List   | False | ロケーションIDのカンマ区切りリスト   |

**例:**

```bash theme={null}
curl -X GET -L 'https://api.products.kameleoon.com/search' \
             -H 'Content-Type: application/json' \
             -d '{
   "did":"abc123",
   "sid":"xyz456",
   "shop_id":"demoShop",
   "type":"instant_search",
   "search_query":"decon",
}'
```

#### b. フル検索 (full\_search)

フィルター、カテゴリー、ページネーション、並べ替えを含む詳細な結果を表示するには、フル検索を使用します。

**エンドポイント:**

```
GET https://api.products.kameleoon.com/search
```

| 名前             | 型             | 必須    | 説明                           |
| :------------- | :------------ | :---- | :--------------------------- |
| `did`          | string        | True  | Device ID（クッキーから取得）          |
| `sid`          | string        | True  | Session ID（クッキーから取得）         |
| `shop_id`      | string        | True  | KameleoonストアID               |
| `type`         | string        | True  | `"full_search"`              |
| `search_query` | string        | True  | ユーザーの検索入力                    |
| `locations`    | List          | False | ロケーションIDのカンマ区切りリスト           |
| `limit`        | Integer       | False | 結果の最大数                       |
| `offset`       | Integer       | False | ページネーション用のオフセット              |
| `extended`     | Integer/Empty | False | `1` で完全な商品データを返します           |
| `sort_by`      | String        | False | 並べ替え基準: `popular`、`price` など |
| `order`        | String        | False | 並べ替え順: `asc` または `desc`      |
| `brands`       | List          | False | ブランドリストでフィルタリング              |
| `categories`   | List          | False | カテゴリーリストでフィルタリング             |
| `filters`      | String        | False | 商品パラメータ用のエスケープされたJSON文字列     |
| `price_min`    | Integer       | False | 最低価格                         |
| `price_max`    | Integer       | False | 最高価格                         |
| `exclude`      | List          | False | 除外する商品ID                     |

```bash theme={null}
curl -X GET -L 'https://api.products.kameleoon.com/search' \
             -H 'Content-Type: application/json' \
             -d '{
   "did":"abc123",
   "sid":"xyz456",
   "shop_id":"demoShop",
   "type":"full_search",
   "search_query":"decon",
   "limit":"10",
   "extended":"1",
   "sort_by":"price",
   "order":"asc",
}'
```

フィルタリングの詳細については、[フィルターセクション](#フィルターの適用)を参照してください。

### 4. レスポンスを統合する

#### a. インスタント検索

リクエストが成功すると、APIは直接ページに挿入するためのHTMLスニペットを、カスタムレンダリング用の商品およびカテゴリーデータと併せて返します。

<Frame>
  ![Instant Search](https://storage.googleapis.com/kameleoon-storage-documentation/developers/images/api-tutorial/instant-search.jpg)
</Frame>

モバイルアプリケーションの場合、JSONの商品およびカテゴリーの配列を使用して、ネイティブなインターフェースを設計してください。

##### サンプルレスポンス

```json theme={null}
{
    "search_query": "decon",
    "collections": [],
    "products_total": 1,
    "products": [
        {
            "name": "VANS | SK8-HI DECON (CUTOUT)| LEAVES\/WHITE",
            "url": "\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=instant_search&recommended_code=decon",
            "category_ids": [
                "1",
                "2",
                "295508017316"
            ],
            "barcode": "VN-05-white-4",
            "vendor_code": "VA",
            "brand": "Vans",
            "leftovers": "lot",
            "rating": 5,
            "fashion_sizes": [
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "10"
            ],
            "fashion_feature": "adult",
            "fashion_gender": "m",
            "fashion_wear_type": "shoe",
            "fashion_original_sizes": [
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "10"
            ],
            "picture": "https:\/\/images.products.kameleoon.com\/resize-images\/180\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
            "categories": [
                {
                    "id": "1",
                    "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
                    "name": "Men",
                    "level": "1",
                    "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon"
                },
                {
                    "id": "2",
                    "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
                    "name": "Women",
                    "level": "1",
                    "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon"
                },
                {
                    "id": "295508017316",
                    "parent_id": "1",
                    "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
                    "name": "Men - Sneakers",
                    "level": "2",
                    "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon"
                }
            ],
            "price_formatted": "$ 179",
            "price_full_formatted": "$ 179.95",
            "price": 179,
            "price_full": 179.95,
            "image_url": "https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484",
            "image_url_handle": "\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484",
            "image_url_resized": {
                "120": "https:\/\/images.products.kameleoon.com\/resize-images\/120\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "140": "https:\/\/images.products.kameleoon.com\/resize-images\/140\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "160": "https:\/\/images.products.kameleoon.com\/resize-images\/160\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "180": "https:\/\/images.products.kameleoon.com\/resize-images\/180\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "200": "https:\/\/images.products.kameleoon.com\/resize-images\/200\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "220": "https:\/\/images.products.kameleoon.com\/resize-images\/220\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "310": "https:\/\/images.products.kameleoon.com\/resize-images\/310\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "520": "https:\/\/images.products.kameleoon.com\/resize-images\/520\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "original": "https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484"
            },
            "url_handle": "\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=instant_search&recommended_code=decon",
            "currency": "$",
            "_id": "3927252",
            "id": "VN-05-white-4",
            "stock_quantity": 19,
            "fashion_colors": [
                "white"
            ],
            "params": [
                {
                    "key": "Size",
                    "values": [
                        "4"
                    ]
                },
                {
                    "key": "Color",
                    "values": [
                        "white"
                    ]
                }
            ],
            "group_id": "_3927252_"
        }
    ],
    "categories": [
        {
            "id": "1",
            "name": "Men",
            "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "count": 1
        },
        {
            "id": "2",
            "name": "Women",
            "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "count": 1
        },
        {
            "id": "295508017316",
            "name": "Men - Sneakers",
            "parent": "1",
            "url": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=instant_search&recommended_code=decon",
            "count": 1
        }
    ],
    "clarification": true,
    "requests_count": 1,
    "queries": [],
    "html": "<div class=\"KameleoonProducts-search-wrapper\"> <div class=\"KameleoonProducts-search-container\"> <div class=\"KameleoonProducts-search-group\"> <div class=\"KameleoonProducts-search-group-title\"> Categories <\/div> <div class=\"KameleoonProducts-search-group-description\"> <a class=\"KameleoonProducts-search-row\" data-id=\"1\" data-remote=\"true\" href=\"\/collections\/all?recommended_by=instant_search&recommended_code=decon\"><span>Men <\/span><\/a> <a class=\"KameleoonProducts-search-row\" data-id=\"2\" data-remote=\"true\" href=\"\/collections\/all?recommended_by=instant_search&recommended_code=decon\"><span>Women <\/span><\/a> <a class=\"KameleoonProducts-search-row\" data-id=\"295508017316\" data-remote=\"true\" href=\"\/collections\/all?recommended_by=instant_search&recommended_code=decon\"><span>Men - Sneakers <\/span><\/a> <\/div> <\/div> <\/div> <div class=\"KameleoonProducts-search-container\" id=\"KameleoonProducts_search_products\"> <div class=\"KameleoonProducts-search-group KameleoonProducts-search-products\"> <div class=\"KameleoonProducts-search-group-title\"> Possible item matches <\/div> <div class=\"KameleoonProducts-search-group-description\"> <a class=\"KameleoonProducts-search-product\" href=\"\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=instant_search&recommended_code=decon\"> <div class=\"KameleoonProducts-search-product__image\" style=\"background-image: url(&#39;https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484&#39;)\"><\/div> <div class=\"KameleoonProducts-search-product__name\"> VANS | SK8-HI DECON (CUTOUT)| LEAVES\/WHITE <\/div> <div class=\"KameleoonProducts-search-product__price\"> $ 179.95 <\/div> <\/a> <\/div> <\/div> <\/div> <div class=\"KameleoonProducts-search-close\"><\/div><\/div>"
}
```

#### a. フル検索

**フル検索** を統合すると、結果表示用の **HTMLスニペット** も提供されます。

レスポンスには、`categories` 配列に加えて `brands` および `filters` 配列も含まれます。

<Note>
  `filters` 配列には、商品の `params` フィールドからのキーと値が含まれます。これらを使用してフィルターインターフェースを構築してください。
</Note>

フル検索結果ページの例:

<Frame>
  ![Full Search](https://storage.googleapis.com/kameleoon-storage-documentation/developers/images/api-tutorial/full-search.jpg)
</Frame>

#### フィルターの適用

以下の例は、上記の画像で選択されたフィルターを含むフル検索リクエストを示しています。

```json theme={null}
{
   "did":"abc123",
   "shop_id":"9fa630bf863db7a87fc6d5fd2a188f",
   "type":"full_search",
   "search_query":"vans",
   "input_query":"vans",
   "categories":"295508017316",
   "filters":{"Color":["white"],"Size":["4"]},
   "brands":"vans"

}
```

##### サンプルレスポンス

```json theme={null}
{
    "search_query": "decon",
    "collections": [],
    "products_total": 1,
    "products": [
        {
            "name": "VANS | SK8-HI DECON (CUTOUT)| LEAVES\/WHITE",
            "url": "\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=full_search&recommended_code=decon",
            "category_ids": [
                "1",
                "2",
                "295508017316"
            ],
            "barcode": "VN-05-white-4",
            "vendor_code": "VA",
            "brand": "Vans",
            "leftovers": "lot",
            "rating": 5,
            "fashion_sizes": [
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "10"
            ],
            "fashion_feature": "adult",
            "fashion_gender": "m",
            "fashion_wear_type": "shoe",
            "fashion_original_sizes": [
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "10"
            ],
            "picture": "https:\/\/images.products.kameleoon.com\/resize-images\/180\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
            "categories": [
                {
                    "id": "1",
                    "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
                    "name": "Men",
                    "level": "1",
                    "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon"
                },
                {
                    "id": "2",
                    "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
                    "name": "Women",
                    "level": "1",
                    "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon"
                },
                {
                    "id": "295508017316",
                    "parent_id": "1",
                    "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
                    "name": "Men - Sneakers",
                    "level": "2",
                    "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon"
                }
            ],
            "price_formatted": "$ 179",
            "price_full_formatted": "$ 179.95",
            "price": 179,
            "price_full": 179.95,
            "image_url": "https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484",
            "image_url_handle": "\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484",
            "image_url_resized": {
                "120": "https:\/\/images.products.kameleoon.com\/resize-images\/120\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "140": "https:\/\/images.products.kameleoon.com\/resize-images\/140\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "160": "https:\/\/images.products.kameleoon.com\/resize-images\/160\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "180": "https:\/\/images.products.kameleoon.com\/resize-images\/180\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "200": "https:\/\/images.products.kameleoon.com\/resize-images\/200\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "220": "https:\/\/images.products.kameleoon.com\/resize-images\/220\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "310": "https:\/\/images.products.kameleoon.com\/resize-images\/310\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "520": "https:\/\/images.products.kameleoon.com\/resize-images\/520\/9fa630bf863db7a87fc6d5fd2a188f\/3927252.jpg",
                "original": "https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484"
            },
            "url_handle": "\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=full_search&recommended_code=decon",
            "currency": "$",
            "_id": "3927252",
            "id": "VN-05-white-4",
            "stock_quantity": 19,
            "fashion_colors": [
                "white"
            ],
            "params": [
                {
                    "key": "Size",
                    "values": [
                        "4"
                    ]
                },
                {
                    "key": "Color",
                    "values": [
                        "white"
                    ]
                }
            ],
            "group_id": "_3927252_"
        }
    ],
    "price_range": {
        "min": 179.95000000000002,
        "max": 179.95000000000002
    },
    "price_ranges": [
        {
            "from": 10,
            "count": 1
        }
    ],
    "price_median": 0,
    "filters": {
        "Color": {
            "count": 1,
            "values": {
                "white": 1
            }
        },
        "Size": {
            "count": 1,
            "values": {
                "4": 1
            },
            "ranges": {
                "min": "4",
                "max": "4"
            }
        }
    },
    "brands": [
        {
            "name": "Vans",
            "count": 1
        }
    ],
    "categories": [
        {
            "id": "1",
            "name": "Men",
            "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "count": 1
        },
        {
            "id": "2",
            "name": "Women",
            "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "count": 1
        },
        {
            "id": "295508017316",
            "name": "Men - Sneakers",
            "parent": "1",
            "url": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "url_handle": "\/collections\/all?recommended_by=full_search&recommended_code=decon",
            "count": 1
        }
    ],
    "industrial_filters": {
        "fashion_sizes": [
            {
                "size": 4,
                "count": 1
            },
            {
                "size": 5,
                "count": 1
            },
            {
                "size": 6,
                "count": 1
            },
            {
                "size": 7,
                "count": 1
            },
            {
                "size": 8,
                "count": 1
            },
            {
                "size": 9,
                "count": 1
            },
            {
                "size": 10,
                "count": 1
            }
        ],
        "colors": [
            {
                "color": "white",
                "count": 1
            }
        ]
    },
    "clarification": true,
    "requests_count": 1,
    "html": "<div class=\"KameleoonProducts-search-items\"> <div class=\"KameleoonProducts-search-item\"> <div class=\"KameleoonProducts-search-item-photo\"> <a href=\"\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=full_search&recommended_code=decon\"><img class=\"item_img\" src=\"https:\/\/cdn.shopify.com\/s\/files\/1\/0564\/9180\/2788\/products\/327cd936d9a9c409cd8b36987158013f_grande.jpg?v=1622707484\" \/><\/a> <\/div> <div class=\"KameleoonProducts-search-item-title\"> <a href=\"\/products\/asics-tiger-gel-lyte-v-30-years-of-gel-pack?recommended_by=full_search&recommended_code=decon\">VANS | SK8-HI DECON (CUTOUT)| ...<\/a> <\/div> <div class=\"KameleoonProducts-search-item-price\"> $ 179.95 <\/div> <\/div> <\/div>"
}
```

## 注意事項

* リクエストを行う前に、クッキーがアクセス可能であることを確認してください。
* 商品ページなどで詳細な商品リストを表示するには、`extended=1` を使用したフル検索を利用してください。
* 返されたHTMLをカスタマイズするか、JSONレスポンスを使用してカスタムUIをレンダリングしてください。
