依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Dao層

啟動類加上Elasticsearch的注解:@EnableElasticsearchRepositories
實體類
Elasticsear的基本操作語句(更多請檢視官方文檔):
GET _search
{
"query": {
"match_all": {}
}
}
###建立索引
PUT /mytest
####查詢索引
GET /mytest
####添加文檔 /索引名稱/類型/id
PUT /mytest/user/44
{
"name":"test",
"sex":0,
"age":22
}
###查詢文檔 根據id查詢
GET /mytest/user/60
###查詢目前所有類型的文檔
GET /mytest/user/_search
##根據多個ID批量查詢 查詢多個id分别為1、4
GET /mytest/user/_mget
{
"ids":["1","4"]
}
###查詢年齡為年齡21歲
GET /mytest/user/_search?q=age:22
###查詢年齡30歲-60歲之間 注意:TO 一定要大寫
GET /mytest/user/_search?q=age[30 TO 60]
#term是代表完全比對,即不進行分詞器分析,文檔中必
#包含整個搜尋的詞彙
GET /mytest/user/_search
{
"query": {
"term": {
"name": "小李"
}
}
}
####match查詢相當于模糊,隻包含其中一部分關鍵詞就行
GET /mytest/user/_search
{
"from": 0,
"size": 2,
"query": {
"match": {
"name": "李"
}
}
}
###filter過濾年齡
GET /mytest/user/_search
{
"query": {
"bool": {
"must": [{
"match_all": {}
}],
"filter": {
"range": {
"age": {
"gt": 21,
"lte": 51
}
}
}
}
},
"from": 0,
"size": 10,
"_source": ["name", "age"]
}
GET /mytest/user/_mapping
###建立索引
PUT /myuser
####查詢索引
GET /myuser
###查詢目前所有類型的文檔
GET /myuser/user/_search
####建立文檔類型并且指定類型
POST /myuser/_mapping/user
{
"user": {
"properties": {
"sex": {
"type": "integer"
},
"age": {
"type": "integer"
},
"introduce": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"name": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
}
#{
# "user":{
# "properties":{
# "age":{
# "type":"integer"
# },
# "sex":{
# "type":"integer"
# },
# "name":{
## "type":"text",
# "analyzer":"ik_smart",
# "search_analyzer":"ik_smart"
# },
# "car":{
# "type":"keyword"
#
# }
# }
# }
#
#}
##建立索引 預設是5個主分片及1個副本分片,我們##這裡不需要這麼多,手動指定3個主分片和1個副#本分片:
PUT /mytest2
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}
POST /mytest2/user/_mapping
{
"properties": {
"type":"text",
"analyzer":"ik_max_word",
"search_analyzer": "ik_max_word"
}
}
###通過指令查詢錯誤日志
GET /consumer_log/doc/_search
{
"query": {
"match": {
"message": "14:11:58"
}
}
}
Elasticsearch 基本操作
_mapping映射很坑,修改之煩人
1、注意版本一緻(我是在Windows搭建的,官網下載下傳解壓運作)
elasticsearch配置
啟動:
位址:http://localhost:9200/ 如下圖啟動成功
ik中文分詞器安裝、配置參照(https://blog.csdn.net/mameng1988/article/details/89049189)https://blog.codecp.org/2018/04/15/Elasticsearch中文分詞器IK/
kibana配置
logstash-配置導入資料資料
啟動方式:
通路位址:
package com.iccunion.consumer.controller;
import com.github.pagehelper.Page;
import com.iccunion.common.http.HttpResult;
import com.iccunion.consumer.dao.UserDao;
import com.iccunion.consumer.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
/**
* elasticsearch 基本操作
* @author xds
* 通路路徑:http://127.0.0.1:8004/swagger-ui.html#/
*/
@Api(value = "elasticsearch 基本操作")
@RestController
public class EsController {
@Autowired
private UserDao userReposiory;
//es工具
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
/**
* 添加修改
* @param user
* @return
*/
@ApiOperation(value="添加使用者", notes="添加使用者")
@PostMapping("/addUser")
public User addUser(@ApiParam(name = "使用者對象", value = "填寫使用者對象")@RequestBody User user) {
return userReposiory.save(user);
}
/**
* 根據ID查詢
* @param id
* @return
*/
@ApiOperation(value="根據ID查詢使用者", notes="根據ID查詢使用者")
@GetMapping("/findById")
public Optional<User> findUser( @ApiParam("請輸入使用者id") @RequestParam(value="id") String id) {
return userReposiory.findById(id);
}
/**
* 查詢所有
* @return
*/
@GetMapping("/getAll")
@ApiOperation(value="擷取所有的document,不分頁", notes="擷取所有的document,不分頁")
public List<User> getAll() {
Iterable<User> iterable = userReposiory.findAll();
List<User> list = new ArrayList<>();
iterable.forEach(list::add);
return list;
}
/**
* 根據ID删除
* @param id
* @return
*/
@DeleteMapping("/delete/{id}")
@ApiOperation(value="根據ID删除使用者", notes="根據ID删除使用者")
public HttpResult deleteById(@ApiParam("請輸入使用者id") @PathVariable String id) {
if (StringUtils.isEmpty(id))
return HttpResult.error();
userReposiory.deleteById(id);
return HttpResult.ok();
}
/**
* 根據姓名查詢 廢棄
* @param introduce
* @return
*/
@GetMapping("/searchIntroduce")
@ApiOperation(value="根據使用者介紹查詢使用者資訊", notes="根據使用者介紹查詢使用者資訊")
public HttpResult repSearchName( @ApiParam("請輸入介紹關鍵詞") @RequestParam(value="introduce") String introduce) {
if (StringUtils.isEmpty(introduce))
return HttpResult.error();
return HttpResult.ok(userReposiory.findByIntroduce(introduce));
}
/**
* 分頁查詢
* @param name
* @param pageIndex
* @param pageSize
* @return
*/
@ApiOperation(value="根據姓名模糊分頁查詢", notes="根據姓名模糊分頁查詢")
@GetMapping("/searchName")
public HttpResult search(@ApiParam("請輸入姓名") @RequestParam(value="name")String name,
@ApiParam("頁碼索引(預設為0)") @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
@ApiParam("每頁的使用者顯示數量(預設為2)") @RequestParam(value="pageSize",required=false,defaultValue="2") int pageSize) {
Pageable pageable = new PageRequest(pageIndex, pageSize);
Page<User> users = userReposiory.findByNameLike(name, pageable);
// List<User> list = users.getResult();
return HttpResult.ok(users);
}
/**
* 進階搜尋,全文搜尋
* 高亮顯示參考:https://blog.csdn.net/u014229347/article/details/88895453
* @param keyword 關鍵字
* @param pageIndex 目前頁,從0開始
* @param pageSize 每頁大小
*/
@ApiOperation(value="全文檢索", notes="全文檢索")
@GetMapping("/fullText")
public HttpResult fullText(@ApiParam("請輸入關鍵詞(測試輸入:java入門佐助李)") @RequestParam(value="keyword")String keyword,
@ApiParam("頁碼索引(預設為0)") @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
@ApiParam("每頁的顯示數量(預設為20)") @RequestParam(value="pageSize",required=false,defaultValue="20") int pageSize) {
// 構造分頁對象
Pageable pageable = PageRequest.of(pageIndex, pageSize);
// 構造查詢
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder()
.withPageable(pageable)
;
if (!StringUtils.isEmpty(keyword)) {
searchQueryBuilder.withQuery(QueryBuilders.queryStringQuery(keyword))
;
}
// SearchQuery 這個很關鍵,這是搜尋條件的入口, elasticsearchTemplate 會使用它進行搜尋
SearchQuery searchQuery = searchQueryBuilder.build();
AggregatedPage<User> users = elasticsearchTemplate.queryForPage(searchQuery, User.class);
return HttpResult.ok(users);
}
/**
* 進階搜尋,根據字段進行搜尋
* @param name 名稱
* @param age 年齡
* @param introduce 介紹
* @param pageIndex 目前頁,從0開始
* @param pageSize 每頁大小10
*/
@ApiOperation(value="多條件聯合查詢", notes="多條件聯合查詢")
@GetMapping("/search")
public HttpResult search(@ApiParam("請輸入姓名") @RequestParam(value="name",required = false) String name,
@ApiParam("請輸入年齡") @RequestParam(value="age",required = false) String age,
@ApiParam("請輸入介紹詞") @RequestParam(value="introduce",required = false) String introduce,
@ApiParam("頁碼索引(預設為0)") @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
@ApiParam("每頁的顯示數量(預設為20)") @RequestParam(value="pageSize",required=false,defaultValue="20") int pageSize
) {
// 建構查詢條件
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
if (!StringUtils.isEmpty(name)) {
boolQueryBuilder.must(QueryBuilders.matchQuery("name", name));
}
if (!StringUtils.isEmpty(age)) {
boolQueryBuilder.must(QueryBuilders.matchQuery("age", age));
}
if (!StringUtils.isEmpty(introduce)) {
boolQueryBuilder.must(QueryBuilders.matchQuery("introduce", introduce));
}
// 構造分頁對象
Pageable pageable = PageRequest.of(pageIndex, pageSize);
// 封裝查詢條件
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withPageable(pageable)
.withQuery(boolQueryBuilder)
.build()
;
// 分頁查詢
AggregatedPage<User> users = elasticsearchTemplate.queryForPage(searchQuery, User.class);
return HttpResult.ok(users);
}
}
ELK+kafka日志收集
為什麼要用elk做日志收集系統?
基于es的反向索引原理,是以查詢效率很高,能很快定位,檢視系統問題;我這裡是用kibana查詢,根據系統需要可以內建到自己的項目中.
将錯誤日志,實時同步到logstash,logstash将日志發到es,通過kibana查詢出日志,也可以整合到工程中查詢出來
logstash配置
啟動指令:logstash -f mylog.conf
也可将系統的日志檔案輸出路徑配置到dao配置檔案,每分鐘
啟動方式:這裡我寫了一個conf 是以這樣啟動
請求位址:http://localhost:9600/ 出現如下圖内容則啟動成功