Nestjs教程如何使用Elasticsearch实现全文搜索

最近在学习Nestjs框架,想实现一个全文搜索功能,看到官方文档推荐使用Elasticsearch。但在实际开发过程中遇到几个问题:1) 如何正确配置Nestjs与Elasticsearch的连接?2) 在Nestjs中创建索引和映射的最佳实践是什么?3) 能否提供一个完整的CRUD操作示例,包括索引文档、搜索文档等?4) 对于中文搜索,是否需要特别的分词器配置?希望有经验的大佬能分享下具体实现步骤和注意事项。

3 回复

以下是一个简单的NestJS结合Elasticsearch实现全文搜索的步骤:

  1. 安装依赖:

    npm install [@nestjs](/user/nestjs)/elasticsearch [@elastic](/user/elastic)/elasticsearch
    
  2. 配置Elasticsearch模块: 在app.module.ts中配置Elasticsearch:

    import { Module } from '[@nestjs](/user/nestjs)/common';
    import { ElasticsearchModule } from '[@nestjs](/user/nestjs)/elasticsearch';
    
    [@Module](/user/Module)({
      imports: [
        ElasticsearchModule.register({
          node: 'http://localhost:9200',
        }),
      ],
    })
    export class AppModule {}
    
  3. 创建服务处理搜索逻辑:

    nest g service search
    

    search.service.ts中:

    import { Injectable } from '[@nestjs](/user/nestjs)/common';
    import { Client } from '[@elastic](/user/elastic)/elasticsearch';
    import { InjectElasticsearch } from '[@nestjs](/user/nestjs)/elasticsearch';
    
    [@Injectable](/user/Injectable)()
    export class SearchService {
      constructor(@InjectElasticsearch() private client: Client) {}
    
      async search(query: string) {
        const result = await this.client.search({
          index: 'your_index_name', // 替换为你的索引名
          body: {
            query: {
              multi_match: {
                query,
                fields: ['title^2', 'content'], // 搜索字段及权重
              },
            },
          },
        });
        return result.body.hits.hits.map(hit => hit._source);
      }
    }
    
  4. 创建控制器提供API接口:

    nest g controller search
    

    search.controller.ts中:

    import { Controller, Get, Query } from '[@nestjs](/user/nestjs)/common';
    import { SearchService } from './search.service';
    
    [@Controller](/user/Controller)('search')
    export class SearchController {
      constructor(private readonly searchService: SearchService) {}
    
      @Get()
      async find(@Query('q') query: string) {
        return this.searchService.search(query);
      }
    }
    
  5. 索引数据到Elasticsearch(可以使用Kibana或API)。

  6. 测试接口,如访问/search?q=关键词即可。


要在NestJS中使用Elasticsearch实现全文搜索,你可以按照以下步骤操作:

  1. 安装依赖:

    npm install [@nestjs](/user/nestjs)/elasticsearch elasticsearch
    
  2. 配置Elasticsearch模块: 在app.module.ts中引入[@nestjs](/user/nestjs)/elasticsearch模块,并配置客户端连接信息。

    import { Module } from '[@nestjs](/user/nestjs)/common';
    import { ElasticsearchModule } from '[@nestjs](/user/nestjs)/elasticsearch';
    
    [@Module](/user/Module)({
      imports: [
        ElasticsearchModule.register({
          node: 'http://localhost:9200', // Elasticsearch地址
        }),
      ],
    })
    export class AppModule {}
    
  3. 创建服务: 使用ElasticsearchService来执行查询。例如,创建一个search.service.ts文件。

    import { Injectable } from '[@nestjs](/user/nestjs)/common';
    import { ElasticsearchService } from '[@nestjs](/user/nestjs)/elasticsearch';
    
    [@Injectable](/user/Injectable)()
    export class SearchService {
      constructor(private readonly elasticSearchService: ElasticsearchService) {}
    
      async search(query: string) {
        return this.elasticSearchService.search({
          index: 'your_index_name', // 你的索引名
          body: {
            query: {
              multi_match: {
                query,
                fields: ['title^2', 'content'], // 字段权重
              },
            },
          },
        });
      }
    }
    
  4. 使用服务: 在控制器中注入并调用SearchService

    import { Controller, Get, Query } from '[@nestjs](/user/nestjs)/common';
    import { SearchService } from './search.service';
    
    [@Controller](/user/Controller)('search')
    export class SearchController {
      constructor(private readonly searchService: SearchService) {}
    
      @Get()
      async search(@Query('q') query: string) {
        const result = await this.searchService.search(query);
        return result;
      }
    }
    

这样,你就完成了一个简单的基于NestJS和Elasticsearch的全文搜索功能。记得提前在Elasticsearch中建立好索引和映射。

NestJS与Elasticsearch实现全文搜索教程

基础准备

  1. 首先安装必要的依赖包:
npm install @nestjs/elasticsearch @elastic/elasticsearch
  1. 在NestJS中设置Elasticsearch模块:
// elasticsearch.module.ts
import { Module } from '@nestjs/common';
import { ElasticsearchModule } from '@nestjs/elasticsearch';

@Module({
  imports: [
    ElasticsearchModule.register({
      node: 'http://localhost:9200', // 你的Elasticsearch服务器地址
    }),
  ],
  exports: [ElasticsearchModule],
})
export class SearchModule {}

实现搜索服务

// search.service.ts
import { Injectable } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';

@Injectable()
export class SearchService {
  constructor(private readonly elasticsearchService: ElasticsearchService) {}

  async createIndex(index: string) {
    return this.elasticsearchService.indices.create({ index });
  }

  async indexDocument(index: string, id: string, document: any) {
    return this.elasticsearchService.index({
      index,
      id,
      body: document,
    });
  }

  async search(index: string, text: string) {
    return this.elasticsearchService.search({
      index,
      body: {
        query: {
          multi_match: {
            query: text,
            fields: ['title', 'content'] // 根据你的数据结构调整
          }
        }
      }
    });
  }
}

在控制器中使用

// search.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
import { SearchService } from './search.service';

@Controller('search')
export class SearchController {
  constructor(private readonly searchService: SearchService) {}

  @Get()
  async search(@Query('q') query: string) {
    return this.searchService.search('your_index_name', query);
  }
}

使用建议

  1. 在生产环境中,建议使用环境变量配置Elasticsearch连接
  2. 考虑添加错误处理和日志记录
  3. 对于大数据量,可以研究Elasticsearch的分页和聚合功能
  4. 可以通过设置mapping优化搜索性能

这个基础实现可以让你快速在NestJS应用中集成Elasticsearch全文搜索功能。根据你的具体需求,可以进一步扩展和优化。

回到顶部