From dc9523e5228c03aeb7b23f669bff669bfa03a9ca Mon Sep 17 00:00:00 2001 From: Hongbo Wu Date: Tue, 12 Jul 2022 22:39:49 +0800 Subject: [PATCH] add searchAsYouType in elastic --- packages/api/src/elastic/pages.ts | 47 +++++++++++++++++++++++++ packages/api/test/elastic/index.test.ts | 36 +++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/packages/api/src/elastic/pages.ts b/packages/api/src/elastic/pages.ts index d503e83a1..42089781e 100644 --- a/packages/api/src/elastic/pages.ts +++ b/packages/api/src/elastic/pages.ts @@ -548,3 +548,50 @@ export const deletePagesByParam = async ( return false } } + +export const searchAsYouType = async ( + userId: string, + query: string, + size = 5 +): Promise => { + try { + const { body } = await client.search>({ + 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 [] + } +} diff --git a/packages/api/test/elastic/index.test.ts b/packages/api/test/elastic/index.test.ts index 8b6665d02..9c6d90966 100644 --- a/packages/api/test/elastic/index.test.ts +++ b/packages/api/test/elastic/index.test.ts @@ -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') + }) + }) })