elasticsearch 的搜索结果中缺少 id 字段

id field is missing from search result in elasticsearch

我正在使用 Elasticsearch v8.1.3 和@elastic/elasticsearch ^8.1.0,@nestjs/elasticsearch ^8.1.0。试图实现这样一个简单的搜索功能:

interface PostSearchBody {
  id: number,
  title: string,
  content: string,
  authorId: number
}

interface PostSearchResult {
  hits: {
    total: number;
    hits: Array<{
      _source: PostSearchBody;
    }>;
  };
}

// class PostsSearchService
  async indexPost(post: Post) {
    return this.elasticsearchService.index<PostSearchResult, PostSearchBody>({
      index: this.index,
      body: {
        id: post.id,
        title: post.title,
        content: post.content,
        authorId: post.author.id
      }
    })
  }
 
  async search(text: string) {
    const { body } = 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);
  }

// class PostsService
  async createPost(post: CreatePostDto, user: User) {
    const newPost = await this.postsRepository.create({
      ...post,
      author: user
    });
    await this.postsRepository.save(newPost);
    this.postsSearchService.indexPost(newPost);
    return newPost;
  }
 
  async searchForPosts(text: string) {
    const results = await this.postsSearchService.search(text);
    // result item should contain "id" field, but doesn't :(
    const ids = results.map(result => result.id);
    if (!ids.length) {
      return [];
    }
    return this.postsRepository
      .find({
        where: { id: In(ids) }
      });
  }

searchForPosts 函数中,我认为结果项应该包含“id”字段,但实际上没有。
这是升级后的 elasticsearch 版本的问题还是我做错了什么?

找出其中的问题并弄明白了。
上面的例子最初来自 here 并且 id 没有被提供给索引函数:

  async createPost(post: CreatePostDto, user: User) {
    // await is not meaningful in the below line:
    const newPost = await this.postsRepository.create({
      ...post,
      author: user
    });
    // you need to use the result of saving transaction
    await this.postsRepository.save(newPost);
    this.postsSearchService.indexPost(newPost);
    return newPost;
  }

所以应该是:

  async createPost(post: CreatePostDto, user: User) {
    const newPost = this.postsRepository.create({
      ...post,
      author: user
    });

    const savedPost = await this.postsRepository.save(newPost);
    this.postsSearchService.indexPost(savedPost);
    return savedPost;
  }

现在它按预期工作了!