springboot elasticsearch简单demo

springboot 整合 elasticsearch 非常简单

第一步:引入maven依赖


			org.elasticsearch.client
			transport
			6.0.0
		
		
			org.springframework.data
			spring-data-elasticsearch
            3.0.2.BUILD-SNAPSHOT
		
		
			com.fasterxml.jackson.core
			jackson-databind
			 2.9.4
		
		
			net.java.dev.jna
			jna
			 3.4.0
		

第二步建立连接

                        //连接配置
			Settings settings = Settings.builder()
					.put("cluster.name", "")//这个cluster.name的值必须和es中elasticsearch.yml里的名字一致,否则会报not part of the cluster Cluster 错误
					.put("client.transport.ignore_cluster_name",true)//忽略名字的校验
					.build();
			TransportClient client = new PreBuiltTransportClient(settings)
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
			BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
				SearchItem searchItem = new SearchItem();
				String image=searchItem.getProductImageBig();
                                searchItem.setId(1);
                                searchItem.setProductImageBig("http://123123.jpg");
				String json = JSON.json(searchItem);//直接将对象转成json,在存入es的时候,es会自动检测并预测字段值的类型。当然如果想更加精确可以在SearchItem对象中用@Document注解
				IndexRequestBuilder indexRequestBuilder = client.prepareIndex("数据库名", "表名", String.valueOf(searchItem.getId())).setSource(json);
				bulkRequestBuilder.add(indexRequestBuilder);
				BulkResponse response = bulkRequestBuilder.get();
				log.info("=============response={}",response);
这样就把数据存入es中了,这是最简便的一个demo,如果想在项目中使用,可以对其进行详细配置,这个在下篇文章中会介绍。



你可能感兴趣的:(springboot)