本文章看了下
使用的是6.8的包,但是我本地安装的是7.13.4.居然也能操作,如果是7.x的包的话,就好了,暂时不影响使用。
三大块
rest操作api
package com.tjx.elasticsearch; import org.apache.http.HttpHost; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest public class TestRest { @Test void testRestInsert() throws IOException { //1.连接rest接口 HttpHost http = new HttpHost("127.0.0.1", 9200, "http"); RestClientBuilder restClientBuilder = RestClient.builder(http);//rest构建器 RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);//获取高级客户端对象 //2.封装请求对象 //BulkRequest bulkRequest = new BulkRequest(); //用于批量操作 IndexRequest indexRequest = new IndexRequest("test_rest", "_doc", "1"); HashMap skuMap = new HashMap(); skuMap.put("name","法拉利 LaFerrari Aperta"); skuMap.put("brandName","法拉利"); skuMap.put("categoryName","超级跑车"); HashMap spec = new HashMap(); spec.put("动力","963匹"); spec.put("扭矩","880N/m"); spec.put("车长","4975mm"); spec.put("重量","1250kg"); skuMap.put("spec",spec); skuMap.put("createTime","2017-08-10"); skuMap.put("price",43000000); skuMap.put("saleNum",209); skuMap.put("commentNum",6128746); indexRequest.source(skuMap); //bulkRequest.add(indexRequest); //用于批量操作 //3.获取响应结果 IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); //BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); //用于批量操作 int status = indexResponse.status().getStatus(); System.out.println(status); restHighLevelClient.close(); } @Test void testRestQueryMatch() throws IOException { //1.连接rest接口 HttpHost http = new HttpHost("127.0.0.1", 9200, "http"); RestClientBuilder restClientBuilder = RestClient.builder(http);//rest构建器 RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);//获取高级客户端对象 //2.封装查询请求 SearchRequest searchRequest = new SearchRequest("test_rest"); searchRequest.types("_doc"); //设置查询的类型 //创建查询条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //查询源构建器 MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("categoryName", "超级跑车"); searchSourceBuilder.query(matchQueryBuilder); searchRequest.source(searchSourceBuilder); //3.获取查询结果 SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits searchHits = response.getHits(); long totalHits = searchHits.getTotalHits(); System.out.println("记录数:"+totalHits); SearchHit[] hits = searchHits.getHits(); for (SearchHit hit : hits) { System.out.println(hit.getSourceAsString()); } restHighLevelClient.close(); } @Test void testRestQueryBool() throws IOException { //1.连接rest接口 HttpHost http = new HttpHost("127.0.0.1", 9200, "http"); RestClientBuilder restClientBuilder = RestClient.builder(http);//rest构建器 RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);//获取高级客户端对象 //2.封装查询请求 SearchRequest searchRequest = new SearchRequest("test_rest"); searchRequest.types("_doc"); //设置查询的类型 //创建查询条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //查询源构建器 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //布尔查询构建器 MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "LaFerrari"); boolQueryBuilder.must(matchQueryBuilder); TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "法拉利"); boolQueryBuilder.must(termQueryBuilder); searchSourceBuilder.query(boolQueryBuilder); searchRequest.source(searchSourceBuilder); //3.获取查询结果 SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits searchHits = response.getHits(); long totalHits = searchHits.getTotalHits(); System.out.println("记录数:" + totalHits); SearchHit[] hits = searchHits.getHits(); for (SearchHit hit : hits) { System.out.println(hit.getSourceAsString()); } restHighLevelClient.close(); } @Test void testRestQueryfilter() throws IOException { //1.连接rest接口 HttpHost http = new HttpHost("127.0.0.1", 9200, "http"); RestClientBuilder restClientBuilder = RestClient.builder(http);//rest构建器 RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);//获取高级客户端对象 //2.封装查询请求 SearchRequest searchRequest = new SearchRequest("test_rest"); searchRequest.types("_doc"); //设置查询的类型 //创建查询条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //查询源构建器 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //布尔查询构建器 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "法拉利"); boolQueryBuilder.filter(termQueryBuilder); searchSourceBuilder.query(boolQueryBuilder); searchRequest.source(searchSourceBuilder); //3.获取查询结果 SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits searchHits = response.getHits(); long totalHits = searchHits.getTotalHits(); System.out.println("记录数:" + totalHits); SearchHit[] hits = searchHits.getHits(); for (SearchHit hit : hits) { System.out.println(hit.getSourceAsString()); } restHighLevelClient.close(); } @Test void testRestQueryAggregation() throws IOException { //连接rest接口 HttpHost http = new HttpHost("127.0.0.1", 9200, "http"); RestClientBuilder restClientBuilder = RestClient.builder(http);//rest构建器 RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);//获取高级客户端对象 //封装查询请求 SearchRequest searchRequest = new SearchRequest("test_rest"); searchRequest.types("_doc"); //设置查询的类型 //创建查询条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //查询源构建器 TermsAggregationBuilder aggregation = AggregationBuilders.terms("类型名称").field("categoryName"); searchSourceBuilder.aggregation(aggregation); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); //获取查询结果 SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); Aggregations aggregations = response.getAggregations(); Map<String, Aggregation> map = aggregations.getAsMap(); Terms terms = (Terms) map.get("类型名称"); List<? extends Terms.Bucket> buckets = terms.getBuckets(); for (Terms.Bucket bucket : buckets) { System.out.println(bucket.getKeyAsString()+":"+bucket.getDocCount()); } restHighLevelClient.close(); //高亮设置 // HighlightBuilder highlightBuilder = new HighlightBuilder(); // highlightBuilder.field("name").preTags("<font style='color:red'>").postTags("</font>"); // searchSourceBuilder.highlighter(highlightBuilder); } }
elasticRestTemplate操作es
package com.tjx.elasticsearch; import com.alibaba.fastjson.JSONObject; import com.tjx.elasticsearch.bean.ChildItem; import com.tjx.elasticsearch.bean.Item; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.range.Range; import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.InternalNumericMetricsAggregation; import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.tophits.TopHits; import org.elasticsearch.search.aggregations.metrics.tophits.TopHitsAggregationBuilder; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.ResultsExtractor; import org.springframework.data.elasticsearch.core.ScrolledPage; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; @SpringBootTest public class TestElasticsearchTemplate { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Test void createIndex(){ //创建索引及映射 elasticsearchTemplate.createIndex(Item.class); //创建映射 // elasticsearchTemplate.putMapping(Item.class); } @Test void putMegacorp() { List<String> list=new ArrayList<>(); list.add("sports"); list.add("music"); ChildItem childItem=new ChildItem(100,"taibai"); Item item1=new Item(6L,"John","男",25,list,childItem); Item item2=new Item(7L,"Jane","Smith",32, Arrays.asList("music"),childItem); Item item3=new Item(8L,"Douglas","Fir",35,Arrays.asList("forestry"),childItem); IndexQuery indexQuery1 = new IndexQueryBuilder().withId(String.valueOf(item1.getLd())).withObject(item1).build(); IndexQuery indexQuery2 = new IndexQueryBuilder().withId(String.valueOf(item2.getLd())).withObject(item2).build(); IndexQuery indexQuery3 = new IndexQueryBuilder().withId(String.valueOf(item3.getLd())).withObject(item3).build(); elasticsearchTemplate.bulkIndex(Arrays.asList(indexQuery1,indexQuery2,indexQuery3)); } @Test void testPage() { SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(matchAllQuery()) .withIndices("test_springdata_es") .withPageable(PageRequest.of(0, 10)) .build(); ScrolledPage<Item> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, Item.class); String scrollId = scroll.getScrollId(); List<Item> content = scroll.getContent(); content.forEach(item->{ System.out.println(item); }); System.out.println(scrollId); elasticsearchTemplate.clearScroll(scrollId); } //平均最大最小求和聚合 @Test void testAggregation(){ AvgAggregationBuilder avgAggregationBuilder = AggregationBuilders.avg("taibai").field("price"); // MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("taibai").field("price"); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(avgAggregationBuilder) .withIndices("goods") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.asList().get(0); InternalNumericMetricsAggregation.SingleValue singleValue= (InternalNumericMetricsAggregation.SingleValue) aggregation1; double value = singleValue.value(); System.out.println(value); } //去重 @Test void testAggregationCardinality(){ CardinalityAggregationBuilder aggregationBuilder = AggregationBuilders.cardinality("taibai").field("price"); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(aggregationBuilder) .withIndices("goods") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("taibai"); InternalNumericMetricsAggregation.SingleValue singleValue= (InternalNumericMetricsAggregation.SingleValue) aggregation1; double value = singleValue.value(); System.out.println(value); } //扩展查询 @Test void testAggregationextended_stats(){ ExtendedStatsAggregationBuilder extendedStatsAggregationBuilder = AggregationBuilders.extendedStats("taibai").field("price"); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(extendedStatsAggregationBuilder) .withIndices("goods") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("taibai"); InternalNumericMetricsAggregation.MultiValue multiValue= (InternalNumericMetricsAggregation.MultiValue ) aggregation1; System.out.println(multiValue.value("max")); } //terms词聚合 @Test void testAggregationTerms(){ TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("taibai").field("price"); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(termsAggregationBuilder) .withIndices("goods") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("taibai"); Terms term1 = (Terms)aggregation1; List<? extends Terms.Bucket> buckets = term1.getBuckets(); for (Terms.Bucket bucket : buckets) { System.out.println(bucket.getKey()+"||"+bucket.getDocCount()); } } //top_hits最高匹配权值聚合 @Test void testAggregationtop_hits(){ TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("taibai").field("price"); TopHitsAggregationBuilder topHitsAggregationBuilder = AggregationBuilders.topHits("top").size(3); termsAggregationBuilder.subAggregation(topHitsAggregationBuilder); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(termsAggregationBuilder) .withIndices("goods") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("taibai"); Terms term1 = (Terms)aggregation1; List<? extends Terms.Bucket> buckets = term1.getBuckets(); for (Terms.Bucket bucket : buckets) { System.out.println(bucket.getKey()+"||"+bucket.getDocCount()); Aggregation aggregation = bucket.getAggregations().getAsMap().get("top"); TopHits topHits= (TopHits) aggregation; Iterator<SearchHit> iterator = topHits.getHits().iterator(); while (iterator.hasNext()){ SearchHit next = iterator.next(); Object object=JSONObject.parse(next.getSourceAsString()); System.out.println(object); } } } @Test void testAggregationRange(){ RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("taibai").field("age") .addRange(20,30).addRange(30,40).addRange(40,50); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(rangeAggregationBuilder) .withIndices("bank") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("taibai"); Range range = (Range)aggregation1; List<? extends Range.Bucket> buckets = range.getBuckets(); for (Range.Bucket bucket : buckets) { System.out.println(bucket.getKeyAsString()+"--"+bucket.getDocCount()); } } @Test void testAggregationLast(){ RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("age_range").field("age") .addRange(20,30).addRange(30,40).addRange(40,50); TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("gender_group").field("gender.keyword"); AvgAggregationBuilder aggregationBuilder = AggregationBuilders.avg("balance_avg").field("balance"); termsAggregationBuilder.subAggregation(aggregationBuilder); rangeAggregationBuilder.subAggregation(termsAggregationBuilder); SearchQuery searchQuery = new NativeSearchQueryBuilder().addAggregation(rangeAggregationBuilder) .withIndices("bank") .withTypes("_doc") .build(); Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse response) { return response.getAggregations(); } }); Aggregation aggregation1 = aggregations.getAsMap().get("age_range"); Range range = (Range)aggregation1; List<? extends Range.Bucket> buckets = range.getBuckets(); for (Range.Bucket bucket : buckets) { System.out.println(bucket.getKeyAsString()+"--"+bucket.getDocCount()); Aggregation gender_group = bucket.getAggregations().getAsMap().get("gender_group"); Terms terms=(Terms)gender_group; List<? extends Terms.Bucket> buckets1 = terms.getBuckets(); for (Terms.Bucket bucket1 : buckets1) { System.out.println(bucket1.getKeyAsString()+"--"+bucket1.getDocCount()); Aggregation balance_avg = bucket1.getAggregations().getAsMap().get("balance_avg"); Avg avg= (Avg) balance_avg; System.out.println(avg.getValue()); } } } }
mapper操作es
@Configuration public class TransportClientConfig extends ElasticsearchConfigurationSupport { @Bean public Client elasticsearchClient() throws UnknownHostException { // Settings settings = Settings.builder().put("cluster.name", "taibai").build(); Settings settings = Settings.builder().build(); TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); return client; } @Bean(name = {"elasticsearchOperations", "elasticsearchTemplate"}) public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException { return new ElasticsearchTemplate(elasticsearchClient(), entityMapper()); } @Bean @Override public EntityMapper entityMapper() { ElasticsearchEntityMapper entityMapper = new ElasticsearchEntityMapper(elasticsearchMappingContext(), new DefaultConversionService()); entityMapper.setConversions(elasticsearchCustomConversions()); return entityMapper; } }
GoodMapper
import com.tjx.elasticsearch.bean.Goods; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface GoodsMapper extends ElasticsearchRepository<Goods, String> { List<Goods> findByName(String name); List<Goods> findByName(String name, Pageable pageable); }
TestMapper
package com.tjx.elasticsearch; import com.tjx.elasticsearch.bean.Goods; import com.tjx.elasticsearch.mapper.GoodsMapper; import org.elasticsearch.index.query.*; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; @SpringBootTest class TestMapper { @Autowired GoodsMapper goodsMapper; //添加一条数据 and 修改一条数据 @Test void insertGoods() { SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = simpleDateFormat.format(new Date()); Goods goods=new Goods(1025332689,"","OPPO R17新年版 2500万美颜拍照 6.4英寸水滴屏 光感屏幕指纹 6G+128G 全网通 移动联通电信4G 双卡双待手机", 37400,20,100,"https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", "https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", 10,str,str,"10000243333000",558,"手机","OPPO","{'颜色': '王者荣耀定制版', '版本': 'R17'}",1,1,1,4L); System.out.println(goodsMapper.save(goods)); } //批量插入和批量修改 @Test void insertGoodsList() { List<Goods> list=new ArrayList<>(); SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = simpleDateFormat.format(new Date()); Goods goods=new Goods(1001332689,"","OPPO R17新年版 2500万美颜拍照 6.4英寸水滴屏 光感屏幕指纹 6G+128G 全网通 移动联通电信4G 双卡双待手机", 37400,10000,100,"https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", "https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", 10,str,str,"10000243333000",558,"手机","OPPO","{'颜色': '王者荣耀定制版', '版本': 'R17'}",1,1,1); Goods goods2=new Goods(1001368912,"","OPPO R17新年版 2500万美颜拍照 6.4英寸水滴屏 光感屏幕指纹 6G+128G 全网通 移动联通电信4G 双卡双待手机", 37400,10000,100,"https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", "https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", 10,str,str,"10000243333000",558,"手机","OPPO","{'颜色': '王者荣耀定制版', '版本': 'R17'}",1,1,1); Goods goods3=new Goods(100001402792L,"","OPPO R17新年版 2500万美颜拍照 6.4英寸水滴屏 光感屏幕指纹 6G+128G 全网通 移动联通电信4G 双卡双待手机", 37400,10000,100,"https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", "https://m.360buyimg.com/mobilecms/s720x720_jfs/t1/10441/9/5525/162976/5c177debEaf815b43/3aa7d4dc182cc4d9.jpg!q70.jpg.webp", 10,str,str,"10000243333000",558,"手机","OPPO","{'颜色': '王者荣耀定制版', '版本': 'R17'}",1,1,1); list.add(goods); list.add(goods2); list.add(goods3); goodsMapper.saveAll(list); } //删除数据 @Test void updateGoods() { //删除一条 // goodsMapper.deleteById("1001332689"); //删除所有或者传入集合 删除集合中的数据 goodsMapper.deleteAll(); } //查询数据 @Test void uqueryGoods() { //查询一条数据 // Optional<Goods> goods = goodsMapper.findById("100001402792"); // System.out.println(goods.get()); // System.out.println("===================================="); //查询所有数据 // Iterable<Goods> goodsAll = goodsMapper.findAll(); // Iterator<Goods> goodsIterator = goodsAll.iterator(); // int count=0; // while (goodsIterator.hasNext()){ // Goods goods1 = goodsIterator.next(); // System.out.println(goods1); // count++; // } // System.out.println(count); // System.out.println("===================================="); //分页排序 // page页码 并不是跳过多少数据 //返回数 Pageable pageable=PageRequest.of(1,100,Sort.by(Sort.Direction.ASC, "num")); Page<Goods> goodsPage = goodsMapper.findAll(pageable); Iterator<Goods> goodsIterator = goodsPage.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } @Test void exists(){ //判断文档是否存在 boolean exists = goodsMapper.existsById("文档ID"); } //term查询 @Test void termGoods(){ //主要用于精确匹配哪些值,比如数字,日期,布尔值或 not_analyzed 的字符串(未经分析的文本数据类型) // 搜索前不会再对搜索词进行分词,所以我们的搜索词必须是文档分词集合中的一个。 TermQueryBuilder termQueryBuilder=new TermQueryBuilder("name","2018"); Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(termQueryBuilder,pageable); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //terms查询 @Test void termsGoods(){ //terms 跟 term 有点类似,但 terms 允许指定多个匹配条件。 // 如果某个字段指定了多个值,那么文档需要一起去做匹配 或者关系 TermsQueryBuilder termsQueryBuilder=new TermsQueryBuilder("name","2018","最新","女鞋"); Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(termsQueryBuilder,pageable); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //range查询 @Test void rangelGoods(){ //范围查询 RangeQueryBuilder rangeQueryBuilder=new RangeQueryBuilder("price"); rangeQueryBuilder.gt(20); rangeQueryBuilder.lt(10000); Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(rangeQueryBuilder,pageable); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //exists查询 @Test void existsGoods(){ //exists 查询可以用于查找文档中是否包含指定字段或没有某个字段,类似于SQL语句中的 IS_NULL 条件 //包含这个字段就返回返回这条数据 ExistsQueryBuilder existsQueryBuilder=new ExistsQueryBuilder("category_name"); Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(existsQueryBuilder,pageable); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //match查询 @Test void matchGoods(){ //match查询会先对搜索词进行分词,分词完毕后再逐个对分词结果进行匹配,因此相比于term的精确搜索,match是分词匹配搜索 //如果用 match 下指定了一个确切值,在遇到数字,日期,布尔值或者 not_analyzed 的字符串时,它将为你搜索你给定的值 MatchQueryBuilder matchQueryBuilder=new MatchQueryBuilder("name","2018年最新女鞋"); Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(matchQueryBuilder,pageable); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //bool查询 和 filter 查询 @Test void boolGoods(){ // bool 查询可以用来合并多个条件查询结果的布尔逻辑,它包含一下操作符: // must :: 多个查询条件的完全匹配,相当于 and 。 // must_not :: 多个查询条件的相反匹配,相当于 not 。 // should :: 至少有一个查询条件匹配, 相当于 or 。 BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder(); //搜索2018年价格在1000-2000之内的女鞋 颜色不能是白色的 只能是黑色或者是红色 RangeQueryBuilder rangeQueryBuilder=new RangeQueryBuilder("price"); rangeQueryBuilder.lte(2000); rangeQueryBuilder.gte(1000); MatchQueryBuilder matchQueryBuilder=new MatchQueryBuilder("name","2018女鞋"); MatchQueryBuilder matchQueryBuilder2=new MatchQueryBuilder("spec","蓝色"); boolQueryBuilder.must(rangeQueryBuilder); boolQueryBuilder.must(matchQueryBuilder); boolQueryBuilder.mustNot(matchQueryBuilder2); MatchQueryBuilder matchQueryBuilder3=new MatchQueryBuilder("spec","黑色 红色"); boolQueryBuilder.must(matchQueryBuilder3); TermQueryBuilder termsQueryBuilder=new TermQueryBuilder("num",10000); boolQueryBuilder.filter(termsQueryBuilder); // Pageable pageable=PageRequest.of(0,100); Iterable<Goods> goods = goodsMapper.search(boolQueryBuilder); Iterator<Goods> goodsIterator = goods.iterator(); int count=0; while (goodsIterator.hasNext()){ Goods goods1 = goodsIterator.next(); System.out.println(goods1); count++; } System.out.println(count); } //自定义方法 @Test void testCustom(){ // List<Goods> goodsList = goodsMapper.findByName("2018新款"); // for (Goods goods : goodsList) { // System.out.println(goods); // } //自定义的方法是分词后 and的关系 必须全部满足 List<Goods> goodsList2 = goodsMapper.findByName("2018新款李白",PageRequest.of(1,10)); for (Goods goods : goodsList2) { System.out.println(goods); } } }
pom
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tjx</groupId> <artifactId>elasticsearch_springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>elasticsearch_springboot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <!--<dependency>--> <!--<groupId>org.elasticsearch.plugin</groupId>--> <!--<artifactId>transport-netty4-client</artifactId>--> <!--<version>7.3.2</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.elasticsearch.client</groupId>--> <!--<artifactId>transport</artifactId>--> <!--<version>7.3.2</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.elasticsearch</groupId>--> <!--<artifactId>elasticsearch</artifactId>--> <!--<version>7.3.2</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.elasticsearch.client</groupId>--> <!--<artifactId>elasticsearch-rest-high-level-client</artifactId>--> <!--<version>7.3.2</version>--> <!--</dependency>--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mybatis依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <!-- druid数据源依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
源码git地址: https://gitee.com/hfl-learn-note/elasticsearch_springboot
完