Created
March 3, 2023 14:07
-
-
Save gabrielecanepa/842d53db09de054c57e076a980a3c80d to your computer and use it in GitHub Desktop.
Sync Algolia query suggestion using the current index configuration.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment