springboot integrates elasticsearch

It is very simple to integrate elasticsearch with springboot

Step 1: Introduce maven dependencies

<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>transport</artifactId>
			<version>6.0.0</version>
		</dependency>

The second step is to establish a connection

                        //Connection configuration
			Settings settings = Settings.builder()
					.put("cluster.name", "")//The value of this cluster.name must be the same as the name in elasticsearch.yml in es, otherwise it will report not part of the cluster Cluster error
					.put("client.transport.ignore_cluster_name",true)//Ignore name verification
					.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);//Convert the object directly to json. When storing in es, es will automatically detect and predict the type of field value. Of course, if you want to be more precise, you can annotate the SearchItem object with @Document
				IndexRequestBuilder indexRequestBuilder = client.prepareIndex("database name", "table name", String.valueOf(searchItem.getId())).setSource(json);
				bulkRequestBuilder.add(indexRequestBuilder);
				BulkResponse response = bulkRequestBuilder.get();
				log.info("=============response={}",response);
In this way, the data is stored in es, which is the easiest demo. If you want to use it in the project, you can configure it in detail, which will be introduced in the next article.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324648611&siteId=291194637