<!-- https://developers.silktide.com/guides/load-presence-into-a-warehouse | Get started -->

# Load Presence into a warehouse

This guide copies Presence into tables of your own, so you can report on it beside the rest of your data. It reads the topics and prompts, then each day's answers with their text, mentions and sources, then how often each site is cited. Everything in it is a `GET` and changes nothing in Silktide.

You need an API key, as in the [Quickstart](https://developers.silktide.com/guides/quickstart.md), for a user who can see all the account's markets.

## 1. Find your workspace and markets

Nearly every Presence query takes a `workspaceId`. [Get it](https://developers.silktide.com/v1/presence/setup/get-workspace.md) once:

```bash
curl "https://api.eu.silktide.com/v1/results/accounts/presence/workspaces/table" \
  -H "Authorization: silktide token=$SILKTIDE_API_KEY"
```

A market has an id too, and no operation lists them. Open each market in Silktide and copy the number after `/presence/` in its address: if the address has `/presence/3/`, it is `3`. Put the ids in your job's settings.

## 2. Read every page

Each query answers a page at a time. This reads all of them, and waits when it meets the [rate limit](https://developers.silktide.com/v1/concepts/rate-limits.md):

```javascript
const ORIGIN = "https://api.eu.silktide.com/v1/results/accounts/presence";

async function get(query, args) {
  for (;;) {
    const response = await fetch(`${ORIGIN}/${query}?${new URLSearchParams(args)}`, {
      headers: { Authorization: `silktide token=${process.env.SILKTIDE_API_KEY}` },
    });
    if (response.status === 429 || response.status === 503) {
      const seconds = Number(response.headers.get("Retry-After")) || 5;
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
      continue;
    }
    const body = await response.json();
    if (body.error) throw new Error(`${query}: ${body.error.type} ${body.error.message}`);
    return body.result;
  }
}

async function allRows(query, args) {
  const rows = [];
  for (let page = 1; ; page++) {
    const result = await get(query, { ...args, page, rowsPerPage: 500 });
    rows.push(...result.rows);
    if (result.rows.length === 0 || page >= result.maxPage) return rows;
  }
}
```

Check `body.error` as well as the status: a results query that fails can answer `200` with an error inside. See [Errors](https://developers.silktide.com/v1/concepts/errors.md).

Stop at `maxPage`. Most Presence tables answer a page past the last with the last page again, so a loop that waits for an empty page never ends.

The limit is 75 requests in five seconds to one path, for each key. The path leaves out the query string, so every request for answers counts together, whatever its dates or market. Read one page after another, as above, and wait when you get a `429`.

## 3. Copy topics and prompts

Read these once a day and replace your copy. They are short, and they change as people edit them. Ask for `status:all`, so that a prompt somebody has since deleted still has a row for its old answers to join to.

```javascript
const workspaceId = 1;
const all = { workspaceId, criteria: "status:all" };

const topics = await allRows("topics/table", { ...all, columns: "name,kind,status,updated,description" });
const prompts = await allRows("prompts/table", all);
const brands = await allRows("brands/table", { workspaceId });
```

[Topics](https://developers.silktide.com/v1/presence/setup/get-topics.md) and [prompts](https://developers.silktide.com/v1/presence/setup/get-prompts.md) list every market here. To know which market a topic is in, read them again with each `marketId`. A topic can be in several.

## 4. Copy each day's answers

[Get answers in full](https://developers.silktide.com/v1/presence/answers/get-answers.md) returns each answer with its text, the brands it mentions and the pages it cites. Ask for one market and one whole day at a time, and send `nextAfter` back as `after` until there is no more:

```javascript
async function answersOn(marketId, day) {
  const from = Date.parse(`${day}T00:00:00Z`) / 1000;
  const answers = [];
  let after;
  do {
    const result = await get("answers", {
      marketId,
      from,
      to: from + 86399,
      limit: 200,
      ...(after ? { after } : {}),
    });
    answers.push(...result.responses);
    after = result.nextAfter;
  } while (after);
  return answers.map((answer) => ({ ...answer, marketId, day }));
}
```

It includes the times an assistant showed no answer, or nothing could be measured. When you work out how often a brand is named, count `ok` and `not_shown`, and leave out `unavailable` and `failed`, as Silktide does. Its page has [the other ways](https://developers.silktide.com/v1/presence/answers/get-answers.md) its rows differ from Silktide's reports.

Save each answer under its `responseId`, and its `mentions` and `sources` in tables of their own that carry the `responseId` too. Replace an answer's mentions and sources together, because working them out again gives them new ids.

A topic can be in several markets, so the same answer can come back for more than one. Keep one copy of the answer, and a separate table of `responseId` and `marketId`.

An answer joins to its prompt by `promptId` and its topic by `topicId`.

If you do not need the text, [List answers](https://developers.silktide.com/v1/presence/answers/get-responses.md) has a short row per answer, read with `allRows`.

## 5. Copy the sites answers cite

[Get cited sites](https://developers.silktide.com/v1/presence/sources/get-cited-sites.md) and [Get cited pages](https://developers.silktide.com/v1/presence/sources/get-cited-pages.md) count citations over some dates. Ask for a day, and one assistant at a time, to get a table you can add up by either:

```javascript
async function citedSitesOn(marketId, day, platform) {
  const from = Date.parse(`${day}T00:00:00Z`) / 1000;
  const rows = await allRows("source-hosts/table", {
    workspaceId,
    marketId,
    platforms: platform,
    from,
    to: from + 86399,
  });
  return rows.map((row) => ({ ...row, marketId, day, platform }));
}
```

`citations` can be added across days and assistants. `shareOfCitations` cannot: work it out again from the totals. Nor can `urlCount`, because the same page can be cited on two days.

The ids of the assistants are on [Presence](https://developers.silktide.com/v1/presence.md#assistants).

### Joining a site to the answers that cite it

The `sources` of the answers you copied in step 4 already say which pages each one cites: those where `cited` is true. Join them by `responseId`.

If you did not copy those, a cited site's row does not say which answers cite it. Ask for the answers that cite a site, by its `host`:

```javascript
async function answersCiting(marketId, day, host) {
  const from = Date.parse(`${day}T00:00:00Z`) / 1000;
  const rows = await allRows("responses/table", {
    workspaceId,
    marketId,
    host,
    from,
    to: from + 86399,
    sort: "requestedAt:a",
  });
  return rows.map(({ responseId, citations }) => ({ responseId, host, citations }));
}
```

Each row is one answer and how many times it cites that host, ready to join to your answers by `responseId`. This is at least one request for each site, so keep it to sites you care about: your own, your competitors', and the ones cited most. Use `domain` in place of `host` to include every host under a domain, or `url` for a single page.

## 6. Run it every day

On each run, read the topics, prompts and brands, then the last few days of answers and cited sites for each market, and replace those days in your tables. An answer can arrive hours after it was asked for and keeps the day it was asked for, so a day you have already read can gain answers.

To load history the first time, do the same for each day back to when you started using Presence.

## What else there is

- [Facts](https://developers.silktide.com/v1/presence/accuracy/get-facts.md) and [fact checks](https://developers.silktide.com/v1/presence/accuracy/get-fact-checks.md) say what assistants get right about a brand.
- [Searches](https://developers.silktide.com/v1/presence/searches/get-searches.md) are what assistants looked up before they answered.
- [Ads](https://developers.silktide.com/v1/presence/ads/get-ads.md) and [advertisers](https://developers.silktide.com/v1/presence/ads/get-advertisers.md) came with the answers.
- [News stories](https://developers.silktide.com/v1/presence/news/get-stories.md) are what was published about a market.

To ask questions of Presence with an AI assistant rather than load it, [connect an AI client](https://developers.silktide.com/guides/connect-an-ai-client.md#what-it-can-read-from-presence).
