Elasticsearch enables powerful full-text search capabilities for your applications.
Index Configuration#
1const indexSettings = {
2 settings: {
3 analysis: {
4 analyzer: {
5 autocomplete: {
6 tokenizer: 'standard',
7 filter: ['lowercase', 'edge_ngram_filter'],
8 },
9 },
10 filter: {
11 edge_ngram_filter: {
12 type: 'edge_ngram',
13 min_gram: 2,
14 max_gram: 20,
15 },
16 },
17 },
18 },
19 mappings: {
20 properties: {
21 title: { type: 'text', analyzer: 'autocomplete' },
22 description: { type: 'text' },
23 category: { type: 'keyword' },
24 price: { type: 'float' },
25 },
26 },
27};Search Query#
1const search = async (query: string, filters: Filters) => {
2 const response = await client.search({
3 index: 'products',
4 body: {
5 query: {
6 bool: {
7 must: [{
8 multi_match: {
9 query,
10 fields: ['title^3', 'description'],
11 fuzziness: 'AUTO',
12 },
13 }],
14 filter: filters.category
15 ? [{ term: { category: filters.category } }]
16 : [],
17 },
18 },
19 highlight: { fields: { title: {}, description: {} } },
20 aggs: {
21 categories: { terms: { field: 'category' } },
22 },
23 },
24 });
25
26 return response.hits.hits;
27};PostgreSQL Alternative#
1-- Full-text search with PostgreSQL
2CREATE INDEX idx_search ON products USING GIN(
3 to_tsvector('english', title || ' ' || description)
4);
5
6SELECT *, ts_rank(search_vector, query) AS rank
7FROM products, plainto_tsquery('wireless mouse') query
8WHERE search_vector @@ query
9ORDER BY rank DESC;Choose Elasticsearch for complex search needs, PostgreSQL for simpler requirements.