本人根据github
上提供的案例中文分词地址,带大家用页面方式来操作,如果你还没配置好环境,可以参考我之前写的文章连接地址
一、基本使用
-
1、启动
docker
容器 -
2、浏览器中输入
http://localhost:9100/
访问地址 -
3、创建一个
index
索引(类似创建一个数据库) -
4、插入数据
-
5、查询全部的数据
注意要写
_search
并且内容体中不能有内容体 -
6、根据
_id
修改数据内容体中你写什么就存入什么数据
-
7、根据条件模糊查询数据
二、在nestjs
中集成ElasticSearch
-
1、参考官网地址
-
2、创建一个
nestjs
项目 -
3、安装依赖包
npm i --save @nestjs/elasticsearch @elastic/elasticsearch
-
4、在
App.module.ts
中引入ElasticsearchModule
模块,或者可以和官网一样的单独创建一个模块,然后在根模块中引入import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ElasticsearchModule } from '@nestjs/elasticsearch'; @Module({ imports: [ ElasticsearchModule.register({ node: 'http://localhost:9200', }) ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
-
5、可以直接在服务层中依赖注入
ElasticsearchService
然后对数据的增删改查,这里简单的使用,实际开发中要更加正规点,仅仅为了演示如何在nestjs
中操作import { Injectable } from '@nestjs/common'; import { ElasticsearchService } from '@nestjs/elasticsearch'; @Injectable() export class AppService { constructor( private readonly elasticsearchService: ElasticsearchService ) {} // 添加、修改、删除数据 async bulk(params: any) { return await this.elasticsearchService.bulk(params); } // 查询数据 async search(params: any) { return await this.elasticsearchService.search(params); } }
-
6、添加数据到
ElasticSearch
async bulk() { return await this.elasticsearchService.bulk({ body: [ // 指定的数据库为news, 指定的Id = 1 { index: { _index: 'news', _type: 'doc', _id: '1' } }, { content: '模拟数据插入' } ] }); }
-
7、删除数据(根据
id
删除数据)async bulk() { return await this.elasticsearchService.bulk({ body: [ { delete: { _index: 'news', _type: 'doc', _id: 'UZAgiHgBS54NjNlgPg5j' } }, ] }); }
-
8、修改数据
async bulk() { return await this.elasticsearchService.bulk({ body: [ { update: { _index: 'news', _type: 'doc', _id: 'UpAhiHgBS54NjNlgfA6i' } }, // 仅仅是修改你改的字段,之前有的字段不会被删除 { doc: { content: '我是被修改的数据' } },] }); }
-
9、查询数据(模糊查询)
async search() { return await this.elasticsearchService.search({ index: 'news', type: 'doc', body: { query: { match: { content: '中国', // 模糊查询,有点类型正则中的match } } } }); }
-
10、分页查询数据
async search() { const pageSize = 10; const pageNumber = 1 return await this.elasticsearchService.search({ index: 'news', type: 'doc', body: { from: (pageNumber - 1) * pageSize, // 从哪里开始 size: pageSize, // 查询条数 query: { match: { content: '中国' // 搜索查询到的内容 } } } }); }
-
11、查询数量
async count() { return await this.elasticsearchService.count({ index: 'news', type: 'doc', body: { query: { match: { content: '中国' } } } }); }
-
12、参考API