Skip to content

Instantly share code, notes, and snippets.

@gabrielecanepa
Created March 3, 2023 14:07
Show Gist options
  • Select an option

  • Save gabrielecanepa/842d53db09de054c57e076a980a3c80d to your computer and use it in GitHub Desktop.

Select an option

Save gabrielecanepa/842d53db09de054c57e076a980a3c80d to your computer and use it in GitHub Desktop.

Revisions

  1. Gabriele Canepa created this gist Mar 3, 2023.
    63 changes: 63 additions & 0 deletions sync-query-suggestions.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    import algoliasearch from 'algoliasearch'

    const INDEX_NAME = 'SOURCE_INDEX_NAME' // e.g. 01uat_hmkw_en
    const QUERY_SUGGESTIONS_INDEX_NAME = 'QUERY_SUGGESTIONS_INDEX_NAME' // e.g. 01uat_hmkw_en_query
    const NEW_QUERY_SUGGESTIONS_INDEX_NAME = 'NEW_QUERY_SUGGESTIONS_INDEX_NAME' // e.g. 01uat_hmkw_en_query_suggestions
    const FACET_NAME = 'CATEGORY_FACET_NAME' // e.g. field_category_name.lvl0

    const client = algoliasearch('APP_ID', 'API_KEY')
    const querySuggestionsIndex = client.initIndex(QUERY_SUGGESTIONS_INDEX_NAME)
    const newQuerySuggestionsIndex = client.initIndex(NEW_QUERY_SUGGESTIONS_INDEX_NAME)

    const run = async () => {
    try {
    // 1. Fetch the original query suggestions
    const querySuggestions = []
    await querySuggestionsIndex.browseObjects({
    batch: batch => {
    querySuggestions.push(...batch)
    },
    })

    // 2. Build the corresponding search queries and run them in bulk
    // on the source index
    const queries = querySuggestions.map(querySuggestion => ({
    indexName: INDEX_NAME,
    query: querySuggestion.query,
    facets: [FACET_NAME],
    }))

    const { results } = await client.multipleQueries(queries)

    // 3. For each query, add to the corresponding query suggestion
    // the exact number of hits and category facets (with exact count)
    for (const result of results) {
    // 3.1 Get query, nbHits and category facet from the result
    const { query, nbHits, facets } = result
    const categoryFacet = facets[FACET_NAME]

    // 3.2 Find the corresponding query suggestion
    const querySuggestion = querySuggestions.find(querySuggestion => querySuggestion.query === query)

    // 3.3 Format the category facet to match the format of the original suggestion
    const querySuggestionsFacets = Object.keys(categoryFacet).reduce((arr, facetName) => {
    arr.push({
    value: facetName,
    count: categoryFacet[facetName],
    })
    return arr
    }, [])

    // 3.4 Replace the exact number of hits and category facets in the original query suggestion
    querySuggestion[INDEX_NAME].exact_nb_hits = nbHits
    querySuggestion[INDEX_NAME].facets = { exact_matches: { [FACET_NAME]: querySuggestionsFacets } }
    }

    // 4. Save the new suggestions in another index
    await newQuerySuggestionsIndex.saveObjects(querySuggestions)
    } catch (e) {
    console.error(e)
    }
    }

    run()