本文链接:https://blog.csdn.net/li521wang/article/details/83792552
略
下载地址:https://www.elastic.co/cn/downloads/elasticsearch
将下载的zip包移动到/usr/local/(目录自定)
使用unzip进行解压
启动脚本在bin目录下
使用./elasticsearch命令启动,但是不能使用root用户,因此我们需要创建用户。
#创建用户组
groupadd esgroup
#创建用户并设置密码
useradd esuser -g esgroup -p espassword
#给esuser用户授权
chown -R esuser:esgroup /usr/local/elasticsearch-6.2.4
#切换用户
su esuser
#启动es
./elasticsearch
这样配置启动依然会出现错误:
需要调整JVM的内存大小:
vi bin/elasticsearch
#修改
ES_JAVA_OPTS="-Xms512m -Xmx512m"
再次启动出现
处理第一个错误:
vim /etc/security/limits.conf
#增加
esuser soft nofile 65536
esuser hard nofile 65536
esuser soft nproc 4096
esuser hard nproc 4096
处理第二个错误:
进入limits.d目录下修改配置文件。
vim /etc/security/limits.d/20-nproc.conf
#修改为
esuser soft nproc 4096
处理第三个错误:
vim /etc/sysctl.conf
#增加
vm.max_map_count=655360
执行以下命令生效:
sysctl -p
再次启动成功!
测试连接:curl 127.0.0.1:9200
会看到一下JSON数据:
[root@localhost ~]# curl 127.0.0.1:9200
{
"name" : "rBrMTNx",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "-noR5DxFRsyvAFvAzxl07g",
"version" : {
"number" : "5.1.1",
"build_hash" : "5395e21",
"build_date" : "2016-12-06T12:36:15.409Z",
"build_snapshot" : false,
"lucene_version" : "6.3.0"
},
"tagline" : "You Know, for Search"
}
如果要远程访问需要配置config/elasticsearch.yml
#集群名称
cluster.name: my-application
#远程访问IP 服务器的IP地址
network.host: 192.168.30.128
#远程访问端口
http.port: 9200
还需要开放linux的9200端口号
# --permanent永久生效,没有此参数重启后失效
firewall-cmd --zone=public --add-port=80/tcp --permanent
#重新载入
firewall-cmd --reload
重启Elasticsearch即可远程访问。
Elasticsearch可视化工具可以使用kibana
进入bin。执行下载安装命令。
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.4.2/elasticsearch-analysis-ik-6.4.2.zip
或者直接下载 https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.4.2/elasticsearch-analysis-ik-6.4.2.zip
将zip移动到plugins/ik/(ik目录需要自己创建)如下图所示:
注意:解压的文件需要全部放到ik根目录。否则启动失败
启动es,测试中文分词器:
curl -XGET http://192.168.30.128:9200/_analyze?pretty -H 'Content-Type:application/json' -d'
{
"analyzer": "ik_smart",
"text": "听说看这篇博客的哥们最帅、姑娘最美"
}'
4.1 创建SpringBoot项目
下图是我的项目分包结构:
4.2 pom.xml配置
根据pom的层级依赖发现spring-boot-starter-data-elasticsearch使用的es版本为6.2.2 。因此需要自己引入es的依赖。依赖如下:
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.elasticsearch
elasticsearch
6.4.2
org.elasticsearch.client
transport
6.4.2
org.elasticsearch
elasticsearch
com.alibaba
fastjson
1.2.39
org.apache.commons
commons-lang3
3.4
org.projectlombok
lombok
1.16.20
commons-httpclient
commons-httpclient
3.1
4.2 application.properties文件配置
# Elasticsearch
# 9200端口是用来让HTTP REST API来访问ElasticSearch,而9300端口是传输层监听的默认端口
elasticsearch.ip=192.168.30.128
elasticsearch.port=9300
elasticsearch.pool=5
#注意cluster.name需要与config/elasticsearch.yml中的cluster.name一致
elasticsearch.cluster.name=my-application
server.port=8181
4.3 创建ES配置类
@Configuration
public class ElasticsearchConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class);
/**
* elk集群地址
*/
@Value("${elasticsearch.ip}")
private String hostName;
/**
* 端口
*/
@Value("${elasticsearch.port}")
private String port;
/**
* 集群名称
*/
@Value("${elasticsearch.cluster.name}")
private String clusterName;
/**
* 连接池
*/
@Value("${elasticsearch.pool}")
private String poolSize;
/**
* Bean name default 函数名字
*
* @return
*/
@Bean(name = "transportClient")
public TransportClient transportClient() {
LOGGER.info("Elasticsearch初始化开始。。。。。");
TransportClient transportClient = null;
try {
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name", clusterName) //集群名字
.put("client.transport.sniff", true)//增加嗅探机制,找到ES集群
.put("thread_pool.search.size", Integer.parseInt(poolSize))//增加线程池个数,暂时设为5
.build();
//配置信息Settings自定义
transportClient = new PreBuiltTransportClient(esSetting);
TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
transportClient.addTransportAddresses(transportAddress);
} catch (Exception e) {
LOGGER.error("elasticsearch TransportClient create error!!", e);
}
return transportClient;
}
}
4.4 创建测试实体
@Data
@ToString
@NoArgsConstructor
public class EsModel {
private String id;
private String name;
private int age;
private Date date;
}
创建分页实体
@Data
@ToString
public class EsPage {
/**
* 当前页
*/
private int currentPage;
/**
* 每页显示多少条
*/
private int pageSize;
/**
* 总记录数
*/
private int recordCount;
/**
* 本页的数据列表
*/
private List
4.5 创建ES操作工具类
Elasticsearch JAVA操作有三种客户端:
1、TransportClient
2、JestClient
3、RestClient
还有种是2.3中有的NodeClient,在5.5.1中好像没有了。还有种是spring-data-elasticsearch,这里先以TransportClient来讲解CRUD。
@Component
public class ElasticsearchUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchUtil.class);
@Autowired
private TransportClient transportClient;
private static TransportClient client;
/**
* @PostContruct是spring框架的注解 spring容器初始化的时候执行该方法
*/
@PostConstruct
public void init() {
client = this.transportClient;
}
/**
* 创建索引
*
* @param index
* @return
*/
public static boolean createIndex(String index) {
if (!isIndexExist(index)) {
LOGGER.info("Index is not exits!");
}
CreateIndexResponse indexresponse = client.admin().indices().prepareCreate(index).execute().actionGet();
LOGGER.info("执行建立成功?" + indexresponse.isAcknowledged());
return indexresponse.isAcknowledged();
}
/**
* 删除索引
*
* @param index
* @return
*/
public static boolean deleteIndex(String index) {
if (!isIndexExist(index)) {
LOGGER.info("Index is not exits!");
}
DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
if (dResponse.isAcknowledged()) {
LOGGER.info("delete index " + index + " successfully!");
} else {
LOGGER.info("Fail to delete index " + index);
}
return dResponse.isAcknowledged();
}
/**
* 判断索引是否存在
*
* @param index
* @return
*/
public static boolean isIndexExist(String index) {
IndicesExistsResponse inExistsResponse = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
if (inExistsResponse.isExists()) {
LOGGER.info("Index [" + index + "] is exist!");
} else {
LOGGER.info("Index [" + index + "] is not exist!");
}
return inExistsResponse.isExists();
}
/**
* @Author: LX
* @Description: 判断inde下指定type是否存在
* @Date: 2018/11/6 14:46
* @Modified by:
*/
public boolean isTypeExist(String index, String type) {
return isIndexExist(index)
? client.admin().indices().prepareTypesExists(index).setTypes(type).execute().actionGet().isExists()
: false;
}
/**
* 数据添加,正定ID
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type, String id) {
IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();
LOGGER.info("addData response status:{},id:{}", response.status().getStatus(), response.getId());
return response.getId();
}
/**
* 数据添加
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type) {
return addData(jsonObject, index, type, UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
}
/**
* 通过ID删除数据
*
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
*/
public static void deleteDataById(String index, String type, String id) {
DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
LOGGER.info("deleteDataById response status:{},id:{}", response.status().getStatus(), response.getId());
}
/**
* 通过ID 更新数据
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @return
*/
public static void updateDataById(JSONObject jsonObject, String index, String type, String id) {
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index).type(type).id(id).doc(jsonObject);
client.update(updateRequest);
}
/**
* 通过ID获取数据
*
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @return
*/
public static Map searchDataById(String index, String type, String id, String fields) {
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
if (StringUtils.isNotEmpty(fields)) {
getRequestBuilder.setFetchSource(fields.split(","), null);
}
GetResponse getResponse = getRequestBuilder.execute().actionGet();
return getResponse.getSource();
}
/**
* 使用分词查询,并分页
*
* @param index 索引名称
* @param type 类型名称,可传入多个type逗号分隔
* @param startPage 当前页
* @param pageSize 每页显示条数
* @param query 查询条件
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField 排序字段
* @param highlightField 高亮字段
* @return
*/
public static EsPage searchDataPage(String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
// 需要显示的字段,逗号分隔(缺省为全部字段)
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
//排序字段
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.DESC);
}
// 高亮(xxx=111,aaa=222)
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
//highlightBuilder.preTags("");//设置前缀
//highlightBuilder.postTags("");//设置后缀
// 设置高亮字段
highlightBuilder.field(highlightField);
searchRequestBuilder.highlighter(highlightBuilder);
}
//searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
searchRequestBuilder.setQuery(query);
// 分页应用
searchRequestBuilder.setFrom(startPage).setSize(pageSize);
// 设置是否按查询匹配度排序
searchRequestBuilder.setExplain(true);
//打印的内容 可以在 Elasticsearch head 和 Kibana 上执行查询
LOGGER.info("\n{}", searchRequestBuilder);
// 执行搜索,返回搜索响应信息
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
LOGGER.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
List> sourceList = setSearchResponse(searchResponse, highlightField);
return new EsPage(startPage, pageSize, (int) totalHits, sourceList);
}
return null;
}
/**
* 使用分词查询
*
* @param index 索引名称
* @param type 类型名称,可传入多个type逗号分隔
* @param query 查询条件
* @param size 文档大小限制
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField 排序字段
* @param highlightField 高亮字段
* @return
*/
public static List> searchListData(
String index, String type, QueryBuilder query, Integer size,
String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 设置高亮字段
highlightBuilder.field(highlightField);
searchRequestBuilder.highlighter(highlightBuilder);
}
searchRequestBuilder.setQuery(query);
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
searchRequestBuilder.setFetchSource(true);
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.DESC);
}
if (size != null && size > 0) {
searchRequestBuilder.setSize(size);
}
//打印的内容 可以在 Elasticsearch head 和 Kibana 上执行查询
LOGGER.info("\n{}", searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
LOGGER.info("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
return setSearchResponse(searchResponse, highlightField);
}
return null;
}
/**
* 高亮结果集 特殊处理
*
* @param searchResponse
* @param highlightField
*/
private static List> setSearchResponse(SearchResponse searchResponse, String highlightField) {
List> sourceList = new ArrayList>();
StringBuffer stringBuffer = new StringBuffer();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
searchHit.getSourceAsMap().put("id", searchHit.getId());
if (StringUtils.isNotEmpty(highlightField)) {
System.out.println("遍历 高亮结果集,覆盖 正常结果集" + searchHit.getSourceAsMap());
Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments();
if (text != null) {
for (Text str : text) {
stringBuffer.append(str.string());
}
//遍历 高亮结果集,覆盖 正常结果集
searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString());
}
}
sourceList.add(searchHit.getSourceAsMap());
}
return sourceList;
}
}
4.6 Controller编写
@RestController
@RequestMapping("/es")
public class EsController {
/**
* 测试索引
*/
private String indexName = "test_index";
/**
* 类型
*/
private String esType = "external";
/**
* http://127.0.0.1:8080/es/createIndex
* 创建索引
*
* @param request
* @param response
* @return
*/
@RequestMapping("/createIndex")
public String createIndex(HttpServletRequest request, HttpServletResponse response) {
if (!ElasticsearchUtil.isIndexExist(indexName)) {
ElasticsearchUtil.createIndex(indexName);
} else {
return "索引已经存在";
}
return "索引创建成功";
}
/**
* 插入记录
*
* @return
*/
@RequestMapping("/insertJson")
public String insertJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", DateUtil.formatDate(new Date()));
jsonObject.put("age", 25);
jsonObject.put("name", "j-" + new Random(100).nextInt());
jsonObject.put("date", new Date());
String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
return id;
}
/**
* 插入记录
*
* @return
*/
@RequestMapping("/insertModel")
public String insertModel() {
EsModel esModel = new EsModel();
esModel.setId(DateUtil.formatDate(new Date()));
esModel.setName("m-" + new Random(100).nextInt());
esModel.setAge(30);
esModel.setDate(new Date());
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(esModel);
String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
return id;
}
/**
* 删除记录
*
* @return
*/
@RequestMapping("/delete")
public String delete(String id) {
if (StringUtils.isNotBlank(id)) {
ElasticsearchUtil.deleteDataById(indexName, esType, id);
return "删除id=" + id;
} else {
return "id为空";
}
}
/**
* 更新数据
*
* @return
*/
@RequestMapping("/update")
public String update(String id) {
if (StringUtils.isNotBlank(id)) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", id);
jsonObject.put("age", 31);
jsonObject.put("name", "修改");
jsonObject.put("date", new Date());
ElasticsearchUtil.updateDataById(jsonObject, indexName, esType, id);
return "id=" + id;
} else {
return "id为空";
}
}
/**
* 获取数据
* http://127.0.0.1:8080/es/getData?id=2018-04-25%2016:33:44
*
* @param id
* @return
*/
@RequestMapping("/getData")
public String getData(String id) {
if (StringUtils.isNotBlank(id)) {
Map map = ElasticsearchUtil.searchDataById(indexName, esType, id, null);
return JSONObject.toJSONString(map);
} else {
return "id为空";
}
}
/**
* 查询数据
* 模糊查询
*
* @return
*/
@RequestMapping("/queryMatchData")
public String queryMatchData() {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolean matchPhrase = false;
if (matchPhrase == Boolean.TRUE) {
//不进行分词搜索
boolQuery.must(QueryBuilders.matchPhraseQuery("name", "m"));
} else {
boolQuery.must(QueryBuilders.matchQuery("name", "m-m"));
}
List> list = ElasticsearchUtil.
searchListData(indexName, esType, boolQuery, 10, "name", null, "name");
return JSONObject.toJSONString(list);
}
/**
* 通配符查询数据
* 通配符查询 ?用来匹配1个任意字符,*用来匹配零个或者多个字符
*
* @return
*/
@RequestMapping("/queryWildcardData")
public String queryWildcardData() {
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name.keyword", "j-?466");
List> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
return JSONObject.toJSONString(list);
}
/**
* 正则查询
*
* @return
*/
@RequestMapping("/queryRegexpData")
public String queryRegexpData() {
QueryBuilder queryBuilder = QueryBuilders.regexpQuery("name.keyword", "m--[0-9]{1,11}");
List> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
return JSONObject.toJSONString(list);
}
/**
* 查询数字范围数据
*
* @return
*/
@RequestMapping("/queryIntRangeData")
public String queryIntRangeData() {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("age").from(21)
.to(25));
List> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
return JSONObject.toJSONString(list);
}
/**
* 查询日期范围数据
*
* @return
*/
@RequestMapping("/queryDateRangeData")
public String queryDateRangeData() {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z")
.to("2019-04-25T10:03:08.081Z"));
List> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
return JSONObject.toJSONString(list);
}
/**
* 查询分页
*
* @param startPage 第几条记录开始
* 从0开始
* 第1页 :http://127.0.0.1:8080/es/queryPage?startPage=0&pageSize=2
* 第2页 :http://127.0.0.1:8080/es/queryPage?startPage=2&pageSize=2
* @param pageSize 每页大小
* @return
*/
@RequestMapping("/queryPage")
public String queryPage(String startPage, String pageSize) {
if (StringUtils.isNotBlank(startPage) && StringUtils.isNotBlank(pageSize)) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z")
.to("2019-04-25T10:03:08.081Z"));
EsPage list = ElasticsearchUtil.searchDataPage(indexName, esType, Integer.parseInt(startPage), Integer.parseInt(pageSize), boolQuery, null, null, null);
return JSONObject.toJSONString(list);
} else {
return "startPage或者pageSize缺失";
}
}
}
源码地址:https://github.com/lxwjq/SpringBoot-ElasticSearch