# Search and recommendations

> One query, items.merchant_feed, serves search, similar products, cart suggestions, image search and personalised browse.

Every item query is `items { merchant_feed(...) }`. What you put in `rank_with.multimodal_query` decides what kind of ranking you get:

| You want | Send in `multimodal_query` |
|----------|---------------------------|
| Search results | `text` |
| Products like this one | `item` with `eq` |
| Suggestions for a cart | `item` with `in` |
| Products like a photo | `images` |
| A personalised page | `user: { personalisation: true }` |
| A category page | `user`, plus a `filter_term` for the category |

You can combine them, for example `text` with `user` for personalised search. Item queries need all three [required headers](https://solenya.ai/docs/auth.md#required-headers) and are sent from your backend.

## Shopper IDs

Solenya knows a shopper only by the UUID you send in `Solenya-User-UUID`. Create one per shopper, keep it, and send the same one on item queries and on [tracking events](https://solenya.ai/docs/track.md) (as `solenya_user_uuid`), so searches and later purchases join up. Solenya creates the shopper record the first time it sees the UUID; there is nothing to register.

Use UUIDv7 if you can. In the browser, keep it in a first-party cookie:

```js
import { uuidv7 } from "uuidv7";

function getShopperId() {
  const match = document.cookie.match(/(?:^|; )solenya_user_uuid=([^;]*)/);
  if (match) return match[1];

  const id = uuidv7();
  document.cookie = `solenya_user_uuid=${id}; path=/; max-age=31536000; SameSite=Lax`;
  return id;
}
```

In a React Native app, keep it in storage:

```ts
import AsyncStorage from "@react-native-async-storage/async-storage";
import { uuidv7 } from "uuidv7";

async function getShopperId(): Promise<string> {
  const stored = await AsyncStorage.getItem("solenya_user_uuid");
  if (stored) return stored;

  const id = uuidv7();
  await AsyncStorage.setItem("solenya_user_uuid", id);
  return id;
}
```

Your frontend sends the ID to your backend, and your backend forwards it as the `Solenya-User-UUID` header.

## What comes back

```graphql
query ResultShape {
  items {
    merchant_feed(rank_with: { multimodal_query: { text: "shoes" } }) {
      page(page_size: 25, page_number: 1) {
        rows {
          record {
            id
            title
            price
            price_amount
            currency
          }
          metadata {
            score
            preferred
          }
        }
        page_info {
          has_next_page
          query_uuid
        }
      }
      facets {
        brand(top_n: 10) {
          value
          count
        }
      }
    }
  }
}
```

`page` returns the ranked products and `facets` returns filter counts. Ask for either or both; each is only computed when you ask for it. `page` needs a `multimodal_query`; `facets` doesn't.

### Product fields

`record` has the feed's fields under their feed names: `id`, `item_group_id`, `title`, `description`, `link`, `image_link`, `availability`, `brand`, `color`, `size`, `product_type`, `promotion_id` and `custom_label_0` to `custom_label_4`.

| Field | Holds |
|-------|-------|
| `price`, `sale_price` | The text from your feed, such as `"49.99 ZAR"` |
| `price_amount`, `sale_price_amount` | The same price as a number, without the currency |
| `currency` | The three-letter currency code. It can be null. |

`sale_price` and `sale_price_amount` are null on items without a sale price.

### Row and page details

Each row's `metadata` has `score`, the ranking score, and `preferred`, which is true when a [sort preference](https://solenya.ai/docs/search.md#sort-preferences) moved the row up.

| `page_info` field | Meaning |
|-------------------|---------|
| `has_next_page` | True when this page came back full. A full last page also says true, and the next page is then empty. |
| `query_uuid` | Names this one page of results. Send it on the [events](https://solenya.ai/docs/track.md#attribution) it leads to. The next page has a different value. |
| `experiments` | The experiment arms that served this page, each with `experiment_name` and `arm_name`. Empty when no experiment applied. |
| `serving` | The [ranking settings](https://solenya.ai/docs/setup.md#serving-config) that served this page |
| `facets` | Filter counts for the products on this page only |

### One product per group

`distinct_on` decides what counts as a duplicate. Without it, results are distinct by `id`, so each size or colour variant can appear. Pass `distinct_on: { selector: item_group_id }` to show one product per group. The examples here all do. Leave `nested` unset; both selectors are top-level fields.

## Text search

```graphql
query TextSearch {
  items {
    merchant_feed(
      rank_with: { multimodal_query: { text: "blue running shoes" } }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 24) {
        rows {
          record {
            item_group_id
            title
          }
        }
        page_info {
          query_uuid
        }
      }
    }
  }
}
```

Search ranks by meaning, using the index's search model, so a result doesn't have to contain the words the shopper typed.

## Similar products

Pass one product to get products like it:

```graphql
query SimilarProducts {
  items {
    merchant_feed(
      rank_with: {
        multimodal_query: {
          item: { selector: item_group_id, eq: "ADI_GN2901_BLANK" }
        }
      }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 12) {
        rows {
          record {
            item_group_id
            title
          }
        }
      }
    }
  }
}
```

## Cart suggestions

Pass up to 50 products with `in` to get products similar to the set as a whole:

```graphql
query CartSuggestions {
  items {
    merchant_feed(
      rank_with: {
        multimodal_query: {
          item: { selector: id, in: ["ADI_GN2901_BLANK-UK10", "ADI_GN2901_BLANK-UK11"] }
        }
      }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 12) {
        rows {
          record {
            item_group_id
            title
          }
        }
      }
    }
  }
}
```

If some of the products aren't in the index, the response says so in [`extensions.warnings`](https://solenya.ai/docs/errors.md#warnings).

## Image search

Ask Solenya to confirm image search is set up for your index before you build on it. Pass up to 10 image URLs:

```graphql
query ImageSearch {
  items {
    merchant_feed(
      rank_with: {
        multimodal_query: { images: { urls: ["https://shop.example.com/look.jpg"] } }
      }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 24) {
        rows {
          record {
            item_group_id
            title
          }
        }
      }
    }
  }
}
```

### Uploading an image

To send image files instead of URLs, use `files` in place of `urls` (one or the other, not both). Each file must be an image of at most 10 MB. Send the request as a multipart form, following the [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec):

```bash
curl -X POST https://api.solenya.ai/v1/graphql \
  -H "Authorization: Bearer $SOLENYA_API_KEY" \
  -H "Solenya-Index-UUID: $SOLENYA_INDEX_UUID" \
  -H "Solenya-User-UUID: <user_uuid>" \
  -F 'operations={"query":"query ImageUpload($file: Upload!) { items { merchant_feed(rank_with: { multimodal_query: { images: { files: [$file] } } }, distinct_on: { selector: item_group_id }) { page(page_size: 24) { rows { record { item_group_id title } } } } } }","variables":{"file":null}}' \
  -F 'map={"0":["variables.file"]}' \
  -F '0=@look.png;type=image/png'
```

## Personalised pages

Set `user: { personalisation: true }` to rank for this shopper. It draws on what the shopper did before: either every item request they made, or their `view_item` events, depending on the index's [`tracking_mechanism`](https://solenya.ai/docs/setup.md#create-an-index). For a shopper with no history yet, the index's [`cold_start`](https://solenya.ai/docs/setup.md#serving-config) setting decides the order.

```graphql
query ForYou {
  items {
    merchant_feed(
      rank_with: { multimodal_query: { user: { personalisation: true } } }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 24) {
        rows {
          record {
            item_group_id
            title
          }
        }
      }
    }
  }
}
```

Personalisation is off unless you ask for it, and it combines with `text` or `item`.

To preview what one kind of shopper would see, pass `user: { persona_id: <id> }` instead. A persona is one of the shopper types the preference model has learned, each with an `id`, a `name` and a `probability`; `page_info.serving.personas` lists them. `persona_id` can't be combined with `personalisation`, `text`, `item` or `images`.

## Category pages

A category or landing page is a browse: no text, product or image, just the shopper and a filter. Without personalisation, the index's `default_prompt` ranks it.

```graphql
query WomensCategory {
  items {
    merchant_feed(
      rank_with: { multimodal_query: { user: { personalisation: true } } }
      filter_term: {
        where: { record: { product_type: { like: { value: "Home > Women%" } } } }
      }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 24) {
        rows {
          record {
            item_group_id
            title
          }
        }
      }
    }
  }
}
```

## Sort preferences

`rank_with.sort_preferences` moves some products up without removing any. Products that match the first condition come first, then those matching the second, and so on; the rest follow in ranked order. Use `filter_term` instead when products should be left out.

```graphql
query InStockFirst {
  items {
    merchant_feed(
      rank_with: {
        multimodal_query: { text: "summer dress" }
        sort_preferences: [
          { where: { record: { availability: { eq: { value: "in_stock" } } } } }
          { where: { record: { brand: { eq: { value: "Nike" } } } } }
        ]
      }
      distinct_on: { selector: item_group_id }
    ) {
      page(page_size: 24) {
        rows {
          record {
            item_group_id
            availability
            brand
          }
          metadata {
            preferred
          }
        }
      }
    }
  }
}
```

## Changing ranking for one request

`merchant_feed(serving: ...)` overrides the index's [ranking settings](https://solenya.ai/docs/setup.md#serving-config) for one request.

```graphql
query CoolerBrowse {
  items {
    merchant_feed(
      rank_with: { multimodal_query: { user: { personalisation: true } } }
      serving: { temperature: 0.5 }
    ) {
      page(page_size: 24) {
        rows {
          record {
            id
            title
          }
        }
        page_info {
          serving {
            temperature
          }
        }
      }
    }
  }
}
```

## A full search page

Personalised search with filters, filter counts and the second page of results, in one request:

```graphql
query SearchPage {
  items {
    merchant_feed(
      rank_with: {
        multimodal_query: {
          text: "street-wear"
          user: { personalisation: true }
        }
      }
      distinct_on: { selector: item_group_id }
      filter_term: {
        and: [
          { where: { record: { availability: { eq: { value: "in_stock" } } } } }
          { where: { record: { brand: { in: { values: ["adidas", "Converse", "Nike"] } } } } }
          { where: { record: { product_type: { like: { value: "Home > Women%" } } } } }
          { where: { record: { price: { lt: { value: 800 } } } } }
        ]
      }
    ) {
      facets {
        brand(top_n: 10) {
          value
          count
        }
        size {
          value
          count
        }
      }
      page(page_size: 24, page_number: 2) {
        rows {
          record {
            item_group_id
            title
            image_link
            brand
            price
            sale_price
          }
          metadata {
            score
          }
        }
        page_info {
          has_next_page
          query_uuid
        }
      }
    }
  }
}
```

[Filters and facets](https://solenya.ai/docs/filters.md) explains each part of `filter_term` and `facets`.
