add searchAsYouType in elastic

This commit is contained in:
Hongbo Wu 2022-07-12 22:39:49 +08:00 committed by Jackson Harper
parent 31ac511121
commit dc9523e522
2 changed files with 83 additions and 0 deletions

View file

@ -548,3 +548,50 @@ export const deletePagesByParam = async <K extends keyof ParamSet>(
return false
}
}
export const searchAsYouType = async (
userId: string,
query: string,
size = 5
): Promise<Page[]> => {
try {
const { body } = await client.search<SearchResponse<Page>>({
index: INDEX_ALIAS,
body: {
query: {
bool: {
filter: [
{
term: {
userId,
},
},
{
multi_match: {
query,
type: 'bool_prefix',
fields: ['title', 'title._2gram', 'title._3gram'],
},
},
],
},
},
_source: ['title', 'slug'],
size,
},
})
if (body.hits.total.value === 0) {
return []
}
return body.hits.hits.map((hit: { _source: Page; _id: string }) => ({
...hit._source,
id: hit._id,
}))
} catch (e) {
console.error('failed to search as you type in elastic', e)
return []
}
}

View file

@ -17,6 +17,7 @@ import {
deletePagesByParam,
getPageById,
getPageByParam,
searchAsYouType,
searchPages,
updatePage,
} from '../../src/elastic/pages'
@ -339,4 +340,39 @@ describe('elastic api', () => {
expect(deleted).to.be.true
})
})
describe('searchAsYouType', () => {
before(async () => {
// create a testing page
await createPage(
{
content: '',
createdAt: new Date(),
hash: '',
id: '',
pageType: PageType.Article,
readingProgressAnchorIndex: 0,
readingProgressPercent: 0,
savedAt: new Date(),
slug: '',
state: ArticleSavingRequestStatus.Succeeded,
title: 'search as you type',
url: '',
userId,
},
ctx
)
})
after(async () => {
// delete the testing page
await deletePagesByParam({ userId }, ctx)
})
it('searches pages', async () => {
const searchResults = await searchAsYouType(userId, 'search')
expect(searchResults).to.have.lengthOf(1)
expect(searchResults[0].title).to.eq('search as you type')
})
})
})