Elasticsearch安装
-
将压缩包上传到linux的/usr/local目录下执行
tar -zxvf elasticsearch-8.13.1-linux-x86_64.tar.gz
-
创建用户
处于安全考虑es的运行不允许以root用户执行,所以需要先要创建用户sudo adduser es
-
用户赋权
sudo chown -R es:es /usr/local/elasticsearch-8.13.1
-
修改配置文件
修改/usr/local/elasticsearch-8.13.1/config/elasticsearch.yml文件,true改为false
-
启动
进入es的bin目录下cd /usr/local/elasticsearch-8.13.1/bin
切换到新创建的用户
su - es
运行es
./elasticsearch -d
-
验证
执行curl http://127.0.0.1:9200显示
SpringBoot整合Elasticsearch
-
在pom.xml中添加Elasticsearch依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency>
-
配置Elasticsearch连接信息
在application.properties或(application.yml)中配置Elasticsearch连接信息# application.properties spring.elasticsearch.uris=http://localhost:9200 # application.yml spring: elasticsearch: uris: http://localhost:9200
-
代码
import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.company.project.core.Result; import com.company.project.core.ResultGenerator; import com.company.project.model.SysUser; import com.company.project.service.SysUserService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; @Api(value = "UserController", tags = "用户管理") @Slf4j @CrossOrigin @RestController @RequestMapping("/user") public class UserController { @Autowired private SysUserService sysUserService; @Autowired private RestHighLevelClient client; // 设置索引文档的类型 private static final String DEFAULT_TYPE = "_doc"; // 索引名称 private static final String INDEX_NAME = "user"; @ApiOperation(value = "新增用户", notes = "新增用户") @PostMapping("/add") public Result add(@RequestBody SysUser sysUser) { sysUserService.save(sysUser); List<SysUser> list = new ArrayList<>(); list.add(sysUser); BulkRequest request = new BulkRequest(); list.forEach(user -> { request.add(new IndexRequest().index(INDEX_NAME).id(String.valueOf(sysUser.getUserId())) .type(DEFAULT_TYPE).source(JSON.toJSONString(user), XContentType.JSON)); }); client.bulkAsync(request, RequestOptions.DEFAULT, new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { log.info("bulklistener_onResponse count:" + bulkResponse.getItems().length); } @Override public void onFailure(Exception e) { log.error("bulklistener_onFailure body{} e{}", request.requests(), e.getMessage()); } }); return ResultGenerator.genSuccessResult(); } @ApiOperation(value = "删除用户", notes = "删除用户") @ApiImplicitParam(name = "id", value = "用户id", required = true) @PostMapping("/delete") public Result delete(@RequestParam Integer id) { // 删除数据库数据 sysUserService.deleteById(id); // 删除ES数据 DeleteRequest request = new DeleteRequest(); request.id(String.valueOf(id)); // 数据ID request.index(INDEX_NAME); // 索引 request.type(DEFAULT_TYPE); try { client.delete(request, RequestOptions.DEFAULT); } catch (IOException e) { throw new RuntimeException(e); } return ResultGenerator.genSuccessResult(); } @ApiOperation(value = "删除索引", notes = "删除索引") @PostMapping("/deleteIndex") public Result deleteIndex() { DeleteIndexRequest request = new DeleteIndexRequest(INDEX_NAME); try { client.indices().delete(request, RequestOptions.DEFAULT); } catch (IOException e) { throw new RuntimeException(e); } return ResultGenerator.genSuccessResult(); } /** * 根据条件查询 * * @param queryDto * @return */ @ApiOperation(value = "根据条件查询", notes = "根据条件查询") @PostMapping("/queryByConditions") public Result queryByConditions(SysUser queryDto) { List<SysUser> result = new ArrayList<>(); SearchResponse response = queryElasticsearch(queryDto); if (response != null && response.getHits() != null) { Iterator<SearchHit> hitIterator = response.getHits().iterator(); while (hitIterator.hasNext()) { result.add(JSON.parseObject(hitIterator.next().getSourceAsString(), SysUser.class)); } } return ResultGenerator.genSuccessResult(result); } private SearchResponse queryElasticsearch(SysUser queryDto) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (!Objects.isNull(queryDto.getUserId())) { // must:等值查询 boolQueryBuilder.must(QueryBuilders.termQuery("userId", queryDto.getUserId())); } if (queryDto.getCreateStartTime() != null || queryDto.getCreateEndTime() != null) { // rangeQuery区间查询 RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createTime"); if (queryDto.getCreateStartTime() != null) { rangeQueryBuilder.from(queryDto.getCreateStartTime().getTime()); } if (queryDto.getCreateEndTime() != null) { rangeQueryBuilder.to(queryDto.getCreateEndTime().getTime()); } boolQueryBuilder.must(rangeQueryBuilder); } //通配符查询,类似于like查询 if (StrUtil.isNotBlank(queryDto.getUserName())) { boolQueryBuilder.must(QueryBuilders.wildcardQuery("userName", "*" + queryDto.getUserName() + "*")); } // 索引 SearchRequest request = new SearchRequest(INDEX_NAME); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //检索超过10000 ES会报错,这里只返回数量 if (queryDto.getPageNum() * queryDto.getPageSize() > 10000) { queryDto.setPageNum(1); queryDto.setPageSize(0); } // 分页查询 page sourceBuilder.from((queryDto.getPageNum() - 1) * queryDto.getPageSize()); // 分页查询 倒序 sourceBuilder.sort("createTime", SortOrder.DESC); // size sourceBuilder.size(queryDto.getPageSize()); request.source(sourceBuilder.query(boolQueryBuilder)); SearchResponse response = null; try { response = client.search(request, RequestOptions.DEFAULT); } catch (Exception e) { log.error("查询es异常 request{} e{}", queryDto, e.getMessage()); } return response; } /** * 滚动查询 * * @param scrollId * @return */ public SearchResponse scrollSearch(String scrollId) { SearchResponse response = null; SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); scrollRequest.scroll(TimeValue.timeValueSeconds(120)); try { response = client.scroll(scrollRequest, RequestOptions.DEFAULT); } catch (Exception e) { log.error("查询es异常 request{} e{}", scrollId, e.getMessage()); } return response; } }