This commit is contained in:
2025-05-22 03:51:58 +07:00
parent ae7f2cd114
commit 2b81da1f5e
6 changed files with 355 additions and 3 deletions

View File

@@ -0,0 +1,42 @@
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'
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 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);
}
}