ElasticSearch简单使用总结

本文介绍了Elasticsearch的安装和启动,包括双击启动方式,以及如何解决elasticsearch-head的跨域问题。重点讲解了IK分词器的使用,如创建类型和分析文本,并通过实例展示了如何在Kibana中进行搜索、创建、更新、删除索引操作。同时,还提供了Java代码示例,演示了如何进行索引创建、删除、内容添加和查询。最后提到了使用Kibana进行搜索的场景。
摘要由CSDN通过智能技术生成

ElasticSearch总结
ES官网
IK分词器Git地址
Kibana地址
elasticsearch-head

安装地址最好不要带有中文或者空格

ElasticSearch启动方式—双击
在这里插入图片描述

elasticsearch-head 启动方式
在这里插入图片描述
在这里插入图片描述
kibana启动方式–双击
在这里插入图片描述

使用elasticsearch-head 会出现跨域问题
去elasticsearch的config目录找到elasticsearch.yml在配置文件中加入

http.cors.enabled: true
http.cors.allow-origin: "*"

docker中运行elasticsearch

docker run -it -d -p 9200:9200 -p 9300:9300 -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -e "discovery.type=single-node"  -v /home/es/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml:rw  elasticsearch:7.14.2

在kibana中的命令

#使用ik分词器搜索
GET _analyze
{
  "analyzer":"ik_max_word",
  "text": "今天天气真好呢"
}

#使用ik分词器创建类型
PUT shop/
{
  "mappings": {
      "properties":{
        "name":{
          "type":"text",
          "analyzer":"ik_max_word"
        },
        "price":{
          "type":"long"
        }
      }
  }
}
#为fangyuan索引创建数据类型
PUT /fangyuan
{
  "mappings": {
    "properties": {
      "age":{
        "type":"long"
      },
      "name":{
        "type":"text"
      },
      "tags":{
        "type":"text"
      }
    }
  }
}

#添加信息,添加一条索引类型为fangyuan,类型为doc,id设置为1的的内容,可以用PUT也可以用POST
PUT /fangyuan/_doc/1
{
  "name":"地瓜",
  "age":2,
  "tags":"地瓜在睡觉"
}
POST /fangyuan/_doc/2
{
  "name":"大黄",
  "age":2,
  "tags":"吃了就躺着"
}


#修改索引为fangyuan,类型为doc,id为2的内容
POST fangyuan/_doc/2/_update
{
  "doc":{
     "age":"2",
     "tags":"吃饭睡觉打地瓜" 
  }
}
#这种方式如果没有id为2的就是添加,如果有就是修改,这种形式的修改相当于覆盖,没有的字段就是空
POST fangyuan/_doc/2
{
  "doc":{
     "age":"2",
     "tags":"吃饭睡觉打地瓜" 
  }
}

#指定删除索引为fangyuan,类型为doc,id为2的信息
DELETE fangyuan/_doc/2

#删除fangyuan的索引
DELETE fangyuan

#删除所有索引
DELETE all

#获取以fangyuan为索引的信息
GET fangyuan

#获取索引为fangyuan,类型为doc,id为1的信息
GET fangyuan/_doc/1

#查询fangyuan,类型为doc,字段tags 包含’睡觉、睡、觉’的信息
GET /fangyuan/_doc/_search
{
  "query": {
    "match": {
      "tags": "睡觉"
    }
  }
}

#查询索引为fangyuan的,如果age有关2的或tags是有关打架的
GET /fangyuan/_search
{
  "query":{
    "bool": {
      "should":[
          {"match":{
            "age":"2"
          }},
          {"match":{
            "tags":"打架"
          }}
        ]
    }
  }
}
#查询索引为fangyuan的,如果age有关2的并且tags是有关打架的
GET /dog/_search
{
  "query":{
    "bool": {
      "must":[
          {"match":{
            "age":"2"
          }},
          {"match":{
            "tags":"打架"
          }}
        ]
    }
  }
}

#查询索引为fangyuan的,如果age有关2的或tags是有关打架的,返回结果只有name字段
GET /dog/_search
{
  "query":{
    "bool": {
      "should":[
          {"match":{
            "age":"2"
          }},
          {"match":{
            "tags":"打架"
          }}
        ]
    }
  },
  "_source": ["name"]
}

#排序查询--age字段倒序
GET /fangyuan/_search
{
  "query": {
    "match": {
      "tags": "睡觉"
    }
  },
  "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ]
}

#查询结果高亮显示
GET /fangyuan/_search
{
  "query": {
    "match": {
      "tags": "睡觉"
    }
  },
  "highlight": {
    "pre_tags": "<b style='color:red'>",
    "post_tags": "</b>",
    "fields": {"tags":{}}
  }
}

java配置文件

@Bean("restHighLevelClient")
	public RestHighLevelClient restHighLevelClient() {
		RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
		return restHighLevelClient;
	}
/**
	 * 创建索引
	 * @param index
	 * @return
	 */
	@GetMapping("/createIndexES")
	@ApiOperation("创建索引")
	public Object createIndexES(@RequestParam("index") String index) {
		CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
		CreateIndexResponse response =  null;
		try {
			response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}



	/**
	 * 删除索引
	 * @param index
	 * @return
	 */
	@GetMapping("/dropIndexES")
	@ApiOperation("删除索引")
	public Object dropIndexES(@RequestParam("index") String ...index) {
		DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
		AcknowledgedResponse response =  null;
		try {
			response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 根据索引以及id删除内容
	 * @param index
	 * @return
	 */
	@GetMapping("/deleteIndex/{index}/{id}")
	@ApiOperation("根据索引以及id删除内容")
	public Object deleteIndex(@PathVariable("index") String index,@PathVariable("id") String id) {
		DeleteRequest deleteRequest = new DeleteRequest(index, id);
		DeleteResponse response =  null;
		try {
			response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 创建索引内容
	 * @param index
	 * @return
	 */
	@PostMapping("/insertIndex")
	@ApiOperation("创建索引内容")
	public Object insertIndex(@RequestParam("index") String index,@RequestBody Map map) {
		IndexRequest indexRequest = new IndexRequest(index.toLowerCase());//创建索引
		indexRequest.timeout(TimeValue.timeValueSeconds(10));//设置超时时间
		indexRequest.source(map,XContentType.JSON);
		IndexResponse response =  null;
		try {
			response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 查询es内容
	 * @param index  索引
	 * @return
	 */
	@GetMapping("/searchES")
    @ApiOperation("查询es内容--分页")
	public Object searchES(@RequestParam("index") String index,
			               @RequestParam("text") String text,
			               @RequestParam(name = "pageNum",defaultValue = "1") Integer pageNum,
			               @RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize) {
		SearchRequest searchRequest = new SearchRequest(index);
		SearchResponse response = null;
		MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("like", text);
		SearchSourceBuilder builder = new SearchSourceBuilder();
		builder.query(matchQuery);//查询条件
		HighlightBuilder highlightBuilder = new HighlightBuilder();
		highlightBuilder.preTags("<b style=\"color:red\">").postTags("</b>").field("like");
		builder.highlighter(highlightBuilder);
		builder.from(pageNum);//页数
		builder.size(pageSize);//每页条数
		searchRequest.source(builder);
		try {
			response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		SearchHits searchHits = response.getHits();
		return searchHits;
	}
	
	/**
	 * 修改es内容
	 * @param map
	 * @param index
	 * @param id
	 * @return
	 */
	@PostMapping("/updateES/{index}/{id}")
	@ApiOperation("根据索引以及id修改es内容")
	public Object updateES(@RequestBody Map map,
							@PathVariable("index")String index,
							@PathVariable("id")String id) {
		UpdateRequest request = new UpdateRequest(index, id);
		request.doc(map,XContentType.JSON);
		UpdateResponse response = null;
		try {
			response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@PostMapping("/bulkSavaES/{index}")
	@ApiOperation("批量添加es内容")
	public Object bulkSavaES(@PathVariable("index") String index,@RequestBody List<Map> list) {
		BulkRequest bulkRequest = new BulkRequest(index);
		if(list != null && list.size() > 0) {
			list.forEach(map ->{
				bulkRequest.add(new IndexRequest().source(map,XContentType.JSON));
			});
		}
		BulkResponse response = null;
		try {
			response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

使用 kibana 进行搜索
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值