环境准备
- 安装包下载地址:
https://pan.baidu.com/s/16JuTiH-wOXqKoSgAPYUbFA
提取码: tqs2
搭建步骤
1. 安装elasticsearch
开启后不要关闭dos窗口
2. 安装kibana
开启后不要关闭dos窗口
-
解压缩kibana
-
运行kibana -> D:\java\kibana-6.2.2-windows-x86_64\bin\kibana.bat
-
访问路径: http://localhost:5601
3. 创建项目测试
注: 利用
项目树目录:
-
maven 依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>3.1.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
配置文件 -> application.yml
elasticsearch: cluster: name: elasticsearch ip: localhost port: 9300 pool: 5
-
springboot config装配类 -> ElasticSearchConfig
package com.zc.elasticsearch.config; import java.net.InetAddress; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; @Configuration public class ElasticSearchConfig { @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; /** * 构建TransportClient对象 */ @Bean(name = "transportClient") public TransportClient transportClient() { TransportClient transportClient = null; try { // 配置信息 Settings esSetting = Settings.builder() //集群名字 .put("cluster.name", clusterName) //增加嗅探机制,找到ES集群 .put("client.transport.sniff", true) //增加线程池个数,暂时设为5 .put("thread_pool.search.size", Integer.parseInt(poolSize)).build(); //配置信息Settings自定义 transportClient = new PreBuiltTransportClient(esSetting); TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)); transportClient.addTransportAddresses(transportAddress); } catch (Exception e) { System.out.println(e); } return transportClient; } /** * 构建ElasticsearchTemplate对象 */ @Bean public ElasticsearchOperations elasticsearchTemplate() { Client client = transportClient(); if (client != null) { return new ElasticsearchTemplate(client); } else { //弹出异常对象 throw new RuntimeException("初始化Elasticsearch失败!"); } } }
-
controller -> BookController
package com.zc.elasticsearch.contoller; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; @RestController @RequestMapping("/book") public class BookController { @Autowired private TransportClient transportClient; /** * 添加博客索引信息 */ @PostMapping("/add") public ResponseEntity add(@RequestParam(name = "title") String title, @RequestParam(name = "author") String author, @RequestParam(name = "word_count") int wordCount, @RequestParam(name = "publish_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate) { try { XContentBuilder content = XContentFactory.jsonBuilder().startObject().field("title", title).field("author", author).field("word_count", wordCount) .field("publish_date", publishDate.getTime()).endObject(); IndexResponse result = this.transportClient.prepareIndex("blogs", "blog").setSource(content).get(); return new ResponseEntity(result.getId(), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); ; return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } /** * 根据id查询 */ @GetMapping("/get") public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) { if (id.isEmpty()) { return new ResponseEntity((HttpStatus.NOT_FOUND)); } GetResponse result = transportClient.prepareGet("blogs", "blog", id).get(); if (!result.isExists()) { return new ResponseEntity((HttpStatus.NOT_FOUND)); } return new ResponseEntity(result.getSource(), HttpStatus.OK); } /** * 按条件查询 */ @GetMapping("/query") public ResponseEntity query(@RequestParam(name = "author", required = false) String author, @RequestParam(name = "title", required = false) String title, @RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount, @RequestParam(name = "lt_word_count", required = false) Integer ltWordCount) { //设置查询条件 BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); if (author != null) { boolQuery.must(QueryBuilders.matchQuery("author", author)); } if (title != null) { boolQuery.must(QueryBuilders.matchQuery("title", title)); } //按范围查询 RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount); if (ltWordCount != null && ltWordCount > 0) { rangeQuery.to(ltWordCount); } boolQuery.filter(rangeQuery); SearchRequestBuilder builder = this.transportClient.prepareSearch("blogs").setTypes("blog").setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(boolQuery) //设置分页查询 .setFrom(0).setSize(10); System.out.println(builder); SearchResponse response = builder.get(); List<Map<String, Object>> result = new ArrayList<>(); for (SearchHit hit : response.getHits()) { result.add(hit.getSourceAsMap()); } return new ResponseEntity(result, HttpStatus.OK); } }
-
实体类->item
package com.zc.elasticsearch.entity; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "item",type = "docs", shards = 1, replicas = 0) public class Item { @Id private Long id; @Field(type = FieldType.Text, analyzer = "ik_max_word") private String title; //标题 @Field(type = FieldType.Keyword) private String category;// 分类 @Field(type = FieldType.Keyword) private String brand; // 品牌 @Field(type = FieldType.Double) private Double price; // 价格 @Field(index = false, type = FieldType.Keyword) private String images; // 图片地址 }
-
启动项目
-
elasticsearch 创建 index (类似 数据库建库)
-
利用postman调用往里面存数据
+ -
效果图: