Watch It? Track It.

Anche la ricerca è un indice statico: circa 7.000 piccoli file che insieme coprono ogni nome di ogni serie, film e persona, in ogni lingua. Una query ne richiede solo uno.

File

  • https://api.watchittrackit.com/v1/search/manifest.json
  • https://api.watchittrackit.com/v1/search/{build}/tree.json
  • https://api.watchittrackit.com/v1/search/{build}/l/{hex}.json
  • https://api.watchittrackit.com/v1/search/{build}/s/{hex}.json
  • https://api.watchittrackit.com/v1/search/recent.json

Eseguire una query

  1. Leggi v1/search/manifest.json per ottenere l'id della build corrente.
  2. Leggi v1/search/{build}/tree.json. Non cambia mai all'interno di una build, quindi scaricalo una sola volta.
  3. Normalizza la query: convertila in minuscolo, rimuovi accenti e punteggiatura. Cercala tramite la sua parola più lunga che non sia una stopword.
  4. Percorri l'albero con quella parola per trovare il suo file: un bucket in l/ oppure, se la parola termina esattamente su un prefisso di suddivisione, un riepilogo in s/. I nomi dei file sono la codifica esadecimale dei byte UTF-8 del prefisso.
  5. Mantieni le voci in cui ogni parola della query è l'inizio di una parola del nome. Metti per primi i nomi che iniziano con l'intera query, poi ordina per popolarità.
  6. Applica v1/search/recent.json: elenca i record modificati dopo la build. Scarta le voci dell'indice per quei record e usa invece queste. Cambia man mano che i record vengono modificati, quindi aggiungi una query string che cambi ogni pochi minuti (?w= più la finestra di 5 minuti corrente) per ottenere una copia aggiornata.

Voci

Ogni voce è un array:

PosizioneTipoDescrizione
0stringTipo di record.
1numberId del record.
2stringIl nome corrispondente, in qualunque lingua sia.
3numberPosizione all'interno del suo tipo: 1.000.000 è il più popolare.
4stringSlug del record.
5number | nullAnno, per i titoli.
6string | nullPercorso della miniatura.

Esempio (JavaScript)

const BASE = "https://api.watchittrackit.com/v1/search"
const STOPWORDS = new Set(["a", "an", "and", "the", "of", "in", "on", "to", "for", "at", "by", "with", "or",
  "de", "del", "la", "le", "les", "el", "los", "las", "lo", "un", "une", "et", "du", "des", "da", "do", "dos",
  "der", "die", "das", "und", "ein", "eine", "den", "dem", "von", "zu", "il", "i", "e", "di", "y", "en", "het", "een", "van"])

const normalize = (s) => s.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase()
  .replace(/[^\p{L}\p{N}]+/gu, " ").trim()
const hex = (s) => [...new TextEncoder().encode(s)].map((b) => b.toString(16).padStart(2, "0")).join("")

async function search(query) {
  const { build } = await fetch(`${BASE}/manifest.json`).then((r) => r.json())
  const tree = await fetch(`${BASE}/${build}/tree.json`).then((r) => r.json())

  const q = normalize(query)
  const words = q.split(" ").filter(Boolean)
  const real = words.filter((w) => !STOPWORDS.has(w))
  const word = (real.length ? real : words).sort((a, b) => [...b].length - [...a].length)[0]

  // Walk the tree: descend while the prefix is split; stop at a bucket or a summary.
  let key = "", file
  for (const c of word) {
    if (tree[key + c]) { key += c; continue }
    const starts = tree[key] ?? []
    const start = starts.filter((s) => s <= c).pop() ?? starts[0] ?? c
    file = `l/${hex(key + start)}.json`
    break
  }
  file ??= `s/${hex(key)}.json`

  const res = await fetch(`${BASE}/${build}/${file}`)
  let entries = res.ok ? await res.json() : []

  // Records changed since the build replace the index's entries for them.
  // The query string changes every 5 minutes, so caches don't serve an old copy.
  const recent = await fetch(`${BASE}/recent.json?w=${Math.floor(Date.now() / 300000)}`).then((r) => r.json())
  entries = entries.filter(([type, id]) => !(`${type}:${id}` in recent.records))
  entries.push(...Object.values(recent.records).flat())

  const seen = new Set()
  return entries
    .filter((e) => { const n = normalize(e[2]).split(" "); return words.every((w) => n.some((x) => x.startsWith(w))) })
    .sort((a, b) => Number(normalize(b[2]).startsWith(q)) - Number(normalize(a[2]).startsWith(q)) || b[3] - a[3])
    .filter(([type, id]) => !seen.has(`${type}:${id}`) && seen.add(`${type}:${id}`))
    .slice(0, 30)
}

// [["tv", 81189, "Breaking Bad", 999998, "breaking-bad", 2008, "/images/tv/81189/….t.jpg"], …]
console.log(await search("breaking bad"))

L'indice viene ricostruito ogni giorno. I file di una build non cambiano mai, quindi puoi metterli in cache per tutto il tempo che vuoi; cambiano solo il manifest e recent.json.