Skip to content

Commit

Permalink
🐝 Add the ability to prefix algolia index names
Browse files Browse the repository at this point in the history
This is in order to support multiple staging servers having their own
index inside one Algolia staging application.
  • Loading branch information
larsyencken committed Mar 13, 2024
1 parent abfe948 commit 7d4d4bb
Show file tree
Hide file tree
Showing 8 changed files with 39 additions and 13 deletions.
11 changes: 7 additions & 4 deletions baker/algolia/configureAlgolia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import {
} from "../../settings/serverSettings.js"
import { countries } from "@ourworldindata/utils"
import { SearchIndexName } from "../../site/search/searchTypes.js"
import { getIndexName } from "../../site/search/searchClient.js"

export const CONTENT_GRAPH_ALGOLIA_INDEX = "graph"
export const CONTENT_GRAPH_ALGOLIA_INDEX = getIndexName("graph")

export const getAlgoliaClient = (): SearchClient | undefined => {
if (!ALGOLIA_ID || !ALGOLIA_SECRET_KEY) {
Expand Down Expand Up @@ -58,7 +59,7 @@ export const configureAlgolia = async () => {
unretrievableAttributes: ["views_7d", "score"],
}

const chartsIndex = client.initIndex(SearchIndexName.Charts)
const chartsIndex = client.initIndex(getIndexName(SearchIndexName.Charts))

await chartsIndex.setSettings({
...baseSettings,
Expand Down Expand Up @@ -89,7 +90,7 @@ export const configureAlgolia = async () => {
optionalWords: ["vs"],
})

const pagesIndex = client.initIndex(SearchIndexName.Pages)
const pagesIndex = client.initIndex(getIndexName(SearchIndexName.Pages))

await pagesIndex.setSettings({
...baseSettings,
Expand All @@ -112,7 +113,9 @@ export const configureAlgolia = async () => {
disableExactOnAttributes: ["tags"],
})

const explorersIndex = client.initIndex(SearchIndexName.Explorers)
const explorersIndex = client.initIndex(
getIndexName(SearchIndexName.Explorers)
)

await explorersIndex.setSettings({
...baseSettings,
Expand Down
4 changes: 3 additions & 1 deletion baker/algolia/indexChartsToAlgolia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { getAnalyticsPageviewsByUrlObj } from "../../db/model/Pageview.js"
import { Link } from "../../db/model/Link.js"
import { getRelatedArticles } from "../../db/model/Post.js"
import { Knex } from "knex"
import { ALGOLIA_INDEX_PREFIX } from "../../settings/clientSettings.js"

Check warning on line 12 in baker/algolia/indexChartsToAlgolia.ts

View workflow job for this annotation

GitHub Actions / eslint

'ALGOLIA_INDEX_PREFIX' is defined but never used. Allowed unused vars must match /^_/u

Check warning on line 12 in baker/algolia/indexChartsToAlgolia.ts

View workflow job for this annotation

GitHub Actions / eslint

'ALGOLIA_INDEX_PREFIX' is defined but never used. Allowed unused vars must match /^_/u
import { getIndexName } from "../../site/search/searchClient.js"

const computeScore = (record: Omit<ChartRecord, "score">): number => {
const { numRelatedArticles, views_7d } = record
Expand Down Expand Up @@ -114,7 +116,7 @@ const indexChartsToAlgolia = async () => {
return
}

const index = client.initIndex(SearchIndexName.Charts)
const index = client.initIndex(getIndexName(SearchIndexName.Charts))

await db.getConnection()
const records = await getChartsRecords(db.knexInstance())
Expand Down
3 changes: 2 additions & 1 deletion baker/algolia/indexExplorersToAlgolia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { chunkParagraphs } from "../chunk.js"
import { SearchIndexName } from "../../site/search/searchTypes.js"
import { Chart } from "../../db/model/Chart.js"
import { Knex } from "knex"
import { getIndexName } from "../../site/search/searchClient.js"

type ExplorerBlockColumns = {
type: "columns"
Expand Down Expand Up @@ -193,7 +194,7 @@ const indexExplorersToAlgolia = async () => {
}

try {
const index = client.initIndex(SearchIndexName.Explorers)
const index = client.initIndex(getIndexName(SearchIndexName.Explorers))

const knex = db.knexInstance()
const records = await getExplorerRecords(knex)
Expand Down
3 changes: 2 additions & 1 deletion baker/algolia/indexToAlgolia.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
getPostsFromSnapshots,
} from "../../db/model/Post.js"
import { Knex } from "knex"
import { ALGOLIA_INDEX_PREFIX } from "../../settings/clientSettings.js"

interface TypeAndImportance {
type: PageType
Expand Down Expand Up @@ -232,7 +233,7 @@ const indexToAlgolia = async (knex: Knex<any, any[]>) => {
console.error(`Failed indexing pages (Algolia client not initialized)`)
return
}
const index = client.initIndex(SearchIndexName.Pages)
const index = client.initIndex(ALGOLIA_INDEX_PREFIX + SearchIndexName.Pages)

await db.getConnection()
const records = await getPagesRecords(knex)
Expand Down
2 changes: 2 additions & 0 deletions settings/clientSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export const WORDPRESS_URL: string = process.env.WORDPRESS_URL ?? ""

export const ALGOLIA_ID: string = process.env.ALGOLIA_ID ?? ""
export const ALGOLIA_SEARCH_KEY: string = process.env.ALGOLIA_SEARCH_KEY ?? ""
export const ALGOLIA_INDEX_PREFIX: string =
process.env.ALGOLIA_INDEX_PREFIX ?? ""

export const DONATE_API_URL: string =
process.env.DONATE_API_URL ?? "http://localhost:8788/donation/donate"
Expand Down
18 changes: 12 additions & 6 deletions site/search/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import {
} from "../../settings/clientSettings.js"
import { faSearch } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { DEFAULT_SEARCH_PLACEHOLDER } from "./searchClient.js"
import {
DEFAULT_SEARCH_PLACEHOLDER,
getIndexName,
parseIndexName,
} from "./searchClient.js"

type BaseItem = Record<string, unknown>

Expand Down Expand Up @@ -64,7 +68,7 @@ const getItemUrl: AutocompleteSource<BaseItem>["getItemUrl"] = ({ item }) =>
// The slugs we index to Algolia don't include the /grapher/ or /explorers/ directories
// Prepend them with this function when we need them
const prependSubdirectoryToAlgoliaItemUrl = (item: BaseItem): string => {
const indexName = item.__autocomplete_indexName as SearchIndexName
const indexName = parseIndexName(item.__autocomplete_indexName as string)
const subdirectory = indexNameToSubdirectoryMap[indexName]
return `${subdirectory}/${item.slug}`
}
Expand Down Expand Up @@ -111,23 +115,23 @@ const AlgoliaSource: AutocompleteSource<BaseItem> = {
searchClient,
queries: [
{
indexName: SearchIndexName.Pages,
indexName: getIndexName(SearchIndexName.Pages),
query,
params: {
hitsPerPage: 2,
distinct: true,
},
},
{
indexName: SearchIndexName.Charts,
indexName: getIndexName(SearchIndexName.Charts),
query,
params: {
hitsPerPage: 2,
distinct: true,
},
},
{
indexName: SearchIndexName.Explorers,
indexName: getIndexName(SearchIndexName.Explorers),
query,
params: {
hitsPerPage: 1,
Expand All @@ -141,7 +145,9 @@ const AlgoliaSource: AutocompleteSource<BaseItem> = {
templates: {
header: () => <h5 className="overline-black-caps">Top Results</h5>,
item: ({ item, components }) => {
const index = item.__autocomplete_indexName as SearchIndexName
const index = parseIndexName(
item.__autocomplete_indexName as string
)
const indexLabel =
index === SearchIndexName.Charts
? "Chart"
Expand Down
1 change: 1 addition & 0 deletions site/search/SearchPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ function Filters({
const { scopedResults } = useInstantSearch()
if (isHidden) return null

// LARS: does this need updating too?
const resultsByIndexName = keyBy(scopedResults, "indexId")
const hitsLengthByIndexName = mapValues(resultsByIndexName, (results) =>
get(results, ["results", "hits", "length"], 0)
Expand Down
10 changes: 10 additions & 0 deletions site/search/searchClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
ALGOLIA_ID,
ALGOLIA_INDEX_PREFIX,
ALGOLIA_SEARCH_KEY,
} from "../../settings/clientSettings.js"
import insightsClient, { InsightsClient } from "search-insights"
Expand All @@ -8,6 +9,7 @@ import {
getPreferenceValue,
PreferenceType,
} from "../CookiePreferencesManager.js"
import { SearchIndexName } from "./searchTypes.js"

let insightsInitialized = false
const getInsightsClient = (): InsightsClient => {
Expand All @@ -22,6 +24,14 @@ const getInsightsClient = (): InsightsClient => {
return insightsClient
}

export const getIndexName = (index: SearchIndexName | string): string => {
return `${ALGOLIA_INDEX_PREFIX}${index}`
}

export const parseIndexName = (index: string): SearchIndexName => {
return index.substring(ALGOLIA_INDEX_PREFIX.length) as SearchIndexName
}

export const logSiteSearchClick = (
event: Omit<InsightsSearchClickEvent, "eventName">
) => {
Expand Down

0 comments on commit 7d4d4bb

Please sign in to comment.