当前位置: 首页 > wzjs >正文

龙华网站 建设深圳信科兰州新晨诚网络科技有限公司

龙华网站 建设深圳信科,兰州新晨诚网络科技有限公司,淮南网站seo,平谷做网站Elasticsearch8.x集成SpringBoot3.x 配置项目引入依赖添加配置文件导入ca证书到项目中添加配置 实战操作创建mapping创建文档查询更新全量更新删除数据批量操作(bulk)基本搜索复杂布尔搜索嵌套(nested)搜索分页查询滚动分页查询After分页查询词条(terms)聚合日期聚合 配置项目 …

Elasticsearch8.x集成SpringBoot3.x

    • 配置项目
      • 引入依赖
      • 添加配置文件
      • 导入ca证书到项目中
      • 添加配置
    • 实战操作
      • 创建mapping
      • 创建文档
      • 查询更新
      • 全量更新
      • 删除数据
      • 批量操作(bulk)
      • 基本搜索
      • 复杂布尔搜索
      • 嵌套(nested)搜索
      • 分页查询
      • 滚动分页查询
      • After分页查询
      • 词条(terms)聚合
      • 日期聚合

配置项目

引入依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><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></dependency><dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.8.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.3</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.3</version></dependency><dependency><groupId>jakarta.json</groupId><artifactId>jakarta.json-api</artifactId><version>2.0.1</version></dependency>

添加配置文件

application.yaml

spring:elasticsearch:rest:scheme: httpshost: localhostport: 9200username: elasticpassword: 123456crt: classpath:ca.crt

导入ca证书到项目中

从任意一个es容器中,拷贝证书到resources目录下,根据个人的目录来

/usr/share/elasticsearch/config/certs/ca

添加配置

package com.lglbc.elasticsearch;import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.TransportUtils;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;import javax.net.ssl.SSLContext;
import java.io.IOException;/*** @Description TODO* @Author 关注公众号 “乐哥聊编程” 领取资料和源码 * @Date 2023/07/14 21:04*/
@Configuration
public class ElasticConfig {@Value("${spring.elasticsearch.rest.scheme}")private String scheme;@Value("${spring.elasticsearch.rest.host}")private String host;@Value("${spring.elasticsearch.rest.port}")private int port;@Value("${spring.elasticsearch.rest.crt}")private String crt;@Value("${spring.elasticsearch.rest.username}")private String username;@Value("${spring.elasticsearch.rest.password}")private String password;@Autowiredprivate ResourceLoader resourceLoader;@Beanpublic ElasticsearchClient elasticsearchClient() throws IOException {SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(resourceLoader.getResource(crt).getFile());BasicCredentialsProvider credsProv = new BasicCredentialsProvider();credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));RestClient restClient = RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback(hc -> hc.setSSLContext(sslContext).setDefaultCredentialsProvider(credsProv)).build();// Create the transport and the API clientElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);return client;}
}

实战操作

创建mapping

    @Testpublic void testCreateMapping() throws IOException {PutMappingRequest mappingRequest = new PutMappingRequest.Builder().index("lglbc_java_demo").properties("order_no", builder ->builder.keyword(type -> type)).properties("order_time", builder ->builder.date(type -> type.format("yyyy-MM-dd HH:mm:ss"))).properties("good_info", type -> type.nested(nested -> nested.properties("good_price", builder ->builder.double_(subType -> subType)).properties("good_count", builder ->builder.integer(subType -> subType)).properties("good_name", builder ->builder.text(subType ->subType.fields("keyword", subTypeField -> subTypeField.keyword(subSubType -> subSubType)))))).properties("buyer", builder ->builder.keyword(type -> type)).properties("phone", builder ->builder.keyword(type -> type)).build();ElasticsearchIndicesClient indices = elasticsearchClient.indices();if (indices.exists(request -> request.index("lglbc_java_demo")).value()) {indices.delete(request -> request.index("lglbc_java_demo"));}indices.create(request -> request.index("lglbc_java_demo"));indices.putMapping(mappingRequest);}

创建文档

@Testpublic void testAddData() throws IOException {OrderInfo orderInfo = new OrderInfo("1001", new Date(), "李白", "13098762567");List<OrderInfo.GoodInfo> goodInfos = new ArrayList<>();goodInfos.add(new OrderInfo.GoodInfo("苹果笔记本", 30.5d, 30));goodInfos.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));orderInfo.setGoodInfo(goodInfos);IndexRequest<OrderInfo> request = IndexRequest.of(i -> i.index("lglbc_java_demo").id(orderInfo.getOrderNo()).document(orderInfo));OrderInfo orderInfo2 = new OrderInfo("1002", new Date(), "苏轼", "13098762367");List<OrderInfo.GoodInfo> goodInfos2 = new ArrayList<>();goodInfos2.add(new OrderInfo.GoodInfo("华为笔记本", 18.5d, 15));goodInfos2.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));orderInfo2.setGoodInfo(goodInfos2);IndexRequest<OrderInfo> request2 = IndexRequest.of(i -> i.index("lglbc_java_demo").id(orderInfo2.getOrderNo()).document(orderInfo2));elasticsearchClient.index(request);elasticsearchClient.index(request2);}

查询更新

    @Testpublic void testUpdateDataByQuery() throws IOException {UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.term(term -> term.field("order_no").value("1001"))).script(script -> script.inline(inline -> inline.lang("painless").source("ctx._source['buyer'] = 'java 更新->乐哥聊编程'"))));elasticsearchClient.updateByQuery(request);}

全量更新

    @Testpublic void testUpdateData() throws IOException {OrderInfo orderInfo3 = new OrderInfo("1002", new Date(), "苏轼3", "13098762367");List<OrderInfo.GoodInfo> goodInfos3 = new ArrayList<>();goodInfos3.add(new OrderInfo.GoodInfo("华为笔记本", 18.5d, 15));goodInfos3.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));orderInfo3.setGoodInfo(goodInfos3);UpdateRequest request = UpdateRequest.of(i -> i.index("lglbc_java_demo").id(orderInfo3.getOrderNo()).doc(orderInfo3));elasticsearchClient.update(request, OrderInfo.class);}

删除数据

    @Testpublic void testDelete() throws IOException {DeleteRequest request = DeleteRequest.of(i -> i.index("lglbc_java_demo").id("1002"));elasticsearchClient.delete(request);}

批量操作(bulk)

    @Testpublic void testBulkOperation() throws IOException {testCreateMapping();BulkRequest.Builder br = new BulkRequest.Builder();List<OrderInfo> orders = getOrders();for (OrderInfo orderInfo : orders) {br.operations(op -> op.index(idx -> idx.index("lglbc_java_demo").document(orderInfo)));}elasticsearchClient.bulk(br.build());}

基本搜索

    @Testpublic void testBaseSearch() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.term(term -> term.field("order_no").value("1001"))));SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();List<OrderInfo> orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(JSONUtil.toJsonStr(orderInfos));}

复杂布尔搜索

    @Testpublic void testBoolSearch() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.bool(bool -> bool.filter(filterQuery -> filterQuery.term(term -> term.field("buyer").value("李白"))).must(must -> must.term(term -> term.field("order_no").value("1004"))))));SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();List<OrderInfo> orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(JSONUtil.toJsonStr(orderInfos));}

嵌套(nested)搜索

    @Testpublic void testNestedSearch() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.nested(nested -> nested.path("good_info").query(nestedQuery -> nestedQuery.bool(bool -> bool.must(must -> must.range(range -> range.field("good_info.good_count").gte(JsonData.of("16")))).must(must2 -> must2.range(range -> range.field("good_info.good_price").gte(JsonData.of("30")))))))));SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();List<OrderInfo> orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(JSONUtil.toJsonStr(orderInfos));}

分页查询

   @Testpublic void testBasePageSearch() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").from(0).size(2).query(query -> query.matchAll(matchAll -> matchAll)));SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();List<OrderInfo> orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(orderInfos.size());request = SearchRequest.of(i -> i.index("lglbc_java_demo").from(2).size(2).query(query -> query.matchAll(matchAll -> matchAll)));response = elasticsearchClient.search(request, OrderInfo.class);hits = response.hits().hits();orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(orderInfos.size());request = SearchRequest.of(i -> i.index("lglbc_java_demo").from(4).size(2).query(query -> query.matchAll(matchAll -> matchAll)));response = elasticsearchClient.search(request, OrderInfo.class);hits = response.hits().hits();orderInfos = new ArrayList<>();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}System.out.println(orderInfos.size());}

滚动分页查询

@Testpublic void testScrollPageSearch() throws IOException {String scrollId = null;while (true) {List<OrderInfo> orderInfos = new ArrayList<>();if (StringUtils.isBlank(scrollId)) {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").scroll(Time.of(time -> time.time("1m"))).size(2).query(query -> query.matchAll(matchAll -> matchAll)));SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}scrollId = response.scrollId();} else {String finalScrollId = scrollId;ScrollRequest request = ScrollRequest.of(i -> i.scroll(Time.of(time -> time.time("1m"))).scrollId(finalScrollId));ScrollResponse response = elasticsearchClient.scroll(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());}scrollId = response.scrollId();}if (CollectionUtil.isEmpty(orderInfos)) {break;}System.out.println(orderInfos.size());}}

After分页查询

@Testpublic void testAfterPageSearch() throws IOException {final List<FieldValue>[] sortValue = new List[]{new ArrayList<>()};while (true) {List<OrderInfo> orderInfos = new ArrayList<>();SearchRequest request = SearchRequest.of(i -> {SearchRequest.Builder sort1 = i.index("lglbc_java_demo").size(2).sort(Lists.list(SortOptions.of(sort -> sort.field(field -> field.field("order_no").order(SortOrder.Desc)))));if (CollectionUtil.isNotEmpty(sortValue[0])) {sort1.searchAfter(sortValue[0]);}return sort1.query(query -> query.matchAll(matchAll -> matchAll));});SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);List<Hit<OrderInfo>> hits = response.hits().hits();for (Hit hit : hits) {orderInfos.add((OrderInfo) hit.source());sortValue[0] = hit.sort();}if (CollectionUtil.isEmpty(orderInfos)) {break;}System.out.println(orderInfos.size());}}

词条(terms)聚合

@Testpublic void testTermsAgg() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.matchAll(match->match)).aggregations("agg_term_buyer",agg->agg.dateHistogram(dateHistogram->dateHistogram.field("order_time").calendarInterval(CalendarInterval.Day))));SearchResponse<Void> search = elasticsearchClient.search(request, Void.class);Map<String, Aggregate> aggregations = search.aggregations();Aggregate aggregate = aggregations.get("agg_term_buyer");Buckets<StringTermsBucket> buckets = ((StringTermsAggregate) aggregate._get()).buckets();for (StringTermsBucket bucket : buckets.array()) {String key = bucket.key()._toJsonString();long l = bucket.docCount();System.out.println(key+":::"+l);}}

日期聚合

@Testpublic void testDateAgg() throws IOException {SearchRequest request = SearchRequest.of(i -> i.index("lglbc_java_demo").query(query -> query.matchAll(match->match)).aggregations("agg_date_buyer",agg->agg.dateHistogram(dateHistogram->dateHistogram.field("order_time").calendarInterval(CalendarInterval.Day))));SearchResponse<Void> search = elasticsearchClient.search(request, Void.class);Map<String, Aggregate> aggregations = search.aggregations();Aggregate aggregate = aggregations.get("agg_date_buyer");List<DateHistogramBucket> buckets = ((DateHistogramAggregate) aggregate._get()).buckets().array();System.out.println(aggregate);for (DateHistogramBucket bucket : buckets) {String key = bucket.keyAsString();long l = bucket.docCount();System.out.println(key+":::"+l);}}

文章转载自:

http://gDrU9AMR.mjbnp.cn
http://z7Jm67ar.mjbnp.cn
http://gq31s5xi.mjbnp.cn
http://N8lMkzfj.mjbnp.cn
http://j3a4BOv3.mjbnp.cn
http://VFrL831q.mjbnp.cn
http://GinAokU9.mjbnp.cn
http://Mwwcj5xq.mjbnp.cn
http://mHmDjwFv.mjbnp.cn
http://Xxhm1ghK.mjbnp.cn
http://NiWeJ30Z.mjbnp.cn
http://nTTNe1mF.mjbnp.cn
http://tvCSgkQe.mjbnp.cn
http://IyRhTvsW.mjbnp.cn
http://GhHMegnD.mjbnp.cn
http://PFe93Xz7.mjbnp.cn
http://gYuRi9tl.mjbnp.cn
http://BBbftlns.mjbnp.cn
http://3hzgA8VP.mjbnp.cn
http://POOoHZ95.mjbnp.cn
http://09l8g3IC.mjbnp.cn
http://rbi5JtWe.mjbnp.cn
http://aCy4seLV.mjbnp.cn
http://NKqZXgmH.mjbnp.cn
http://wtZtJ3qN.mjbnp.cn
http://t9uOQAC4.mjbnp.cn
http://hPKgsZmT.mjbnp.cn
http://3A2JZZcw.mjbnp.cn
http://84bfPrrT.mjbnp.cn
http://UFsDpEfI.mjbnp.cn
http://www.dtcms.com/wzjs/657328.html

相关文章:

  • 局机关门户网站建设自查报告范文免费人脉推广软件
  • 一般做网站用什么语言建筑培训机构排名前十
  • 东莞网站设计智能 乐云践新wordpress制作小工具
  • dede网站首页加悬浮广告邯郸技术服务类
  • 做系统用哪个网站好网站建设博客
  • 做企业平台网站成本ae做动画教程网站
  • 专业微网站建设罗湖在线
  • 松江营销型网站建设wordpress 4.6下载
  • 学校网站首页网站建设:博采网络
  • 长安网站制作wordpress浮动播放器
  • 大淘客做网站wordpress网站如何搬家
  • 做网站租服务器哪个商城网站建设好
  • 设计和建设企业网站心得和体会wordpress主题ftp
  • 网站一条龙服务网站开发软硬件条件
  • 做美食网站赚钱吗苏州万户网络科技有限公司
  • 产品做网站上海网站建设上海网站制作
  • wordpress返利插件网站排名云优化工具
  • 养老院网站建设最好的ppt模板网站
  • 网站样式侵权微信定制开发 网站开发
  • 杭州市萧山区建设局网站南宁seo咨询
  • 海南网站设计新媒体运营
  • 网站打开网站制作及管理教程
  • 建设工程网站广州湛江哪里有建网站
  • 分类信息网站成都搭建网站查询域名
  • 网站建设费计入哪个科目2018年靖边建设项目招投标网站
  • 网站建设后台实训体会自考大专报名官网入口
  • 网站备案怎么做高端公司网站
  • 搭建 网站 模版百度互联网公司邯郸分公司
  • 如何做行业平台网站武威建设厅网站
  • 公司定制网站建设公司制作企业网站的目的