add elastic search

This commit is contained in:
Phuoc Nguyen
2025-05-22 11:35:14 +07:00
parent 2b81da1f5e
commit efea3d5411
4 changed files with 130 additions and 37 deletions

View File

@@ -1,42 +1,81 @@
import { Injectable } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';
import {Injectable} from '@nestjs/common';
import {ElasticsearchService} from '@nestjs/elasticsearch';
import Post from "./entities/post.entity";
import {PostSearchResult} from "./types/postSearchResult.interface";
import {PostSearchBody} from "./types/postSearchBody.interface";
@Injectable()
export default class PostsSearchService {
index = 'posts'
index = 'posts';
constructor(
private readonly elasticsearchService: ElasticsearchService
) {}
constructor(
private readonly elasticsearchService: ElasticsearchService
) {
}
async indexPost(post: Post) {
return this.elasticsearchService.index<PostSearchBody>({
index: this.index,
body: {
id: post.id,
title: post.title,
content: post.content,
authorId: post.author.id
}
})
}
async indexPost(post: Post) {
return this.elasticsearchService.index<PostSearchBody>({
index: this.index,
document: {
id: post.id,
title: post.title,
content: post.content,
authorId: post.author.id
}
});
}
async search(text: string) {
const result = await this.elasticsearchService.search<PostSearchResult>({
index: this.index,
query: {
multi_match: {
query: text,
fields: ['title', 'content'],
},
},
});
const hits = result.hits.hits;
return hits.map((item) => item._source);
}
async remove(postId: number) {
await this.elasticsearchService.deleteByQuery({
index: this.index,
query: {
match: {
id: postId,
}
}
})
}
async update(post: Post) {
const newBody: PostSearchBody = {
id: post.id,
title: post.title,
content: post.content,
authorId: post.author.id
};
const script = Object.entries(newBody).reduce((result, [key, value]) => {
return `${result} ctx._source.${key}='${value}';`;
}, '');
await this.elasticsearchService.updateByQuery({
index: this.index,
query: {
match: {
id: post.id,
}
},
script: {
source: script
}
});
}
async search(text: string) {
const response = await this.elasticsearchService.search<PostSearchResult>({
index: this.index,
body: {
query: {
multi_match: {
query: text,
fields: ['title', 'content']
}
}
}
})
const hits = body.hits.hits;
return hits.map((item) => item._source);
}
}