Last active
December 9, 2022 09:30
-
-
Save jdgamble555/257df098104a2f754af8d88821a4cdf8 to your computer and use it in GitHub Desktop.
Firestore Full Text Search Angular
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
// set your term | |
// return this.options to your template | |
// see here: https://fireblog.io/blog/post/firestore-full-text-search | |
const n: any = term.split(' ').length; | |
// split words for separate searching... | |
let newTerm: string[] = term.split(' '); | |
// add each word to search term | |
const searchTerms: any = []; | |
for (let i = 0; i < n; i++) { | |
let t = newTerm.join(' '); | |
if (t) { | |
searchTerms.push(t); | |
} | |
newTerm.shift(); | |
} | |
// set your fields | |
const fields = ['content', 'title', 'summary', 'tags']; | |
this.options = this.orQuery(fields, searchTerms); | |
} | |
// combine the queries | |
orQuery(fields: string[], terms: string[]) { | |
const queries: any[] = []; | |
fields.forEach((f: string) => { | |
terms.forEach((t: string) => { | |
queries.push(this.fieldQuery(f, t)); | |
}); | |
}); | |
return combineLatest(queries).pipe( | |
map((arr: any) => arr.reduce((acc: any, cur: any) => acc.concat(cur))), | |
//map((a: any) => a.sort((a, b) => b.relevance - a.relevance)) | |
map((a: any) => a.sort((a: any, b: any) => (a > b ? -1 : 1))) | |
); | |
} | |
fieldQuery(field: string, term: string) { | |
let id = firebase.firestore.FieldPath.documentId(); | |
return this.afs.collection<any>(`_search/posts/${field}`, ref => { | |
return ref.orderBy(id).startAt(term).endAt(term + '~').limit(5); | |
}) | |
.snapshotChanges() | |
.pipe( | |
map((actions: any) => { | |
return actions.map((a: any) => { | |
a['term'] = a.payload.doc.id.split('_').splice(0, 1) + '...'; | |
a['titleURL'] = a.payload.doc.data().titleURL; | |
return a; | |
}) | |
}), | |
take(1), | |
debounceTime(200) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks