This is the 11th day of my participation in the August Wenwen Challenge.More challenges in August

We should start connecting our Java programs to write

Create a new EmptyProject module2. Create a Springboot project. Omitted here.Directory structure after creation.

Note: At this point our es version may be inconsistent with our local version

My local version is 7.6.1

Here we need to fix the version problem in pom.xml

Full of pom. The XML


      
<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.4.4</version>
		<relativePath/> <! -- lookup parent from repository -->
	</parent>
	<groupId>com.es</groupId>
	<artifactId>jj-es-api</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>jj-es-api</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
<! -- Customize our ES version -->
<elasticsearch.version>7.6.1</elasticsearch.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Copy the code

Download the dependency after viewing, our version and local consistent! In this way, the connection can be successfully guaranteed!

Customize our ElasticSearch configuration class

package com.es.jjesapi.config;


import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/ * * *@author fjj
 * @date 2021/4/9 22:34
 */
// Add a comment
    @Configuration
public class ElasticsearchConfig {
        @Bean
    public RestHighLevelClient restHighLevelClient(a){
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("127.0.0.1".9200."http")));
returnclient; }}Copy the code

Take a look at the source code for ElasticSearch integration in Springboot

The core three… But I don’t really understand it.

Simple test Api

Create indexes

package com.es.jjesapi;

import com.es.jjesapi.config.ElasticsearchConfig;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class JjEsApiApplicationTests {
	// Inject our test class
	@Autowired
	@Qualifier("restHighLevelClient")
	private RestHighLevelClient client;

	@Test
	void contextLoads(a) {}@Test
// Create an index, similar to the put index command
	public void CreateIndex(a) throws IOException {
		// A request to create an index
	CreateIndexRequest request = new CreateIndexRequest("fjj-index");
	// Client execution
	IndicesClient indices = client.indices();
	/ / create
	CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);
	/ / output
	System.out.println("response = "+ response); }}Copy the code

The results of

** Gets the index **


@Test
	// Get the index. Equivalent to a database in mysql
	public void GetIndex(a) throws IOException{
		// Request index request
	GetIndexRequest request = new GetIndexRequest("fjj-index");
	// Client execution
	IndicesClient indices = client.indices();
	// Check whether it exists
	boolean b = indices.exists(request,RequestOptions.DEFAULT);
	System.out.println(b);
}
Copy the code

This is the result of existence and returns trueSuppose we get the index and the block that writes the index that we don’t have, the return is

It is important to note that our index is equivalent to a database in Mysql, so we can only determine whether it exists or not.

Remove the index

// Drop index
	@Test
	public void DeleteIndex(a) throws IOException {
		// Request to drop index
		DeleteIndexRequest request = new DeleteIndexRequest("fjj-index");
		// Client execution
		IndicesClient client = this.client.indices();
		// Perform the delete operation
		AcknowledgedResponse delete = client.delete(request, RequestOptions.DEFAULT);
		System.out.println(delete.isAcknowledged());
	}
Copy the code

The results of

Successfully deleted our index

Document operation

1. We need to add the FastJSON dependency before the document operation

<! Add json dependencies -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.66</version>
		</dependency>
Copy the code

2. Write a POJO class to create objects

Add the document

	// Add a document
	@Test
	public void AddDocument(a) throws IOException {
	// Create an object
		User user = new User("Feng Jiaojiao".18."Female");
		// Create the request
		IndexRequest indexRequest = new IndexRequest("fjj-index");
		// Set the request to the same rule as the previous command line put/ fjJ-index /_doc/1
		indexRequest.id("1");
		// Expiration time
		indexRequest.timeout("1s");
		// Put our request in JSON
		indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
		// The client sends the request
		IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
		// View the added information
		System.out.println(index.toString());
		// Check the status
		System.out.println(index.status());
	}
Copy the code

The results of

Added successfully!

Gets whether the script exists

	// Check whether get/index/doc/1 exists
	@Test
	public void GetDocument(a) throws IOException{
	// Get the request
		GetRequest getRequest = new GetRequest("fjj-index"."1");
		// No context for returning _source
		getRequest.fetchSourceContext(new FetchSourceContext(false));
		getRequest.storedFields("_none_");
		// Client execution
		boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
		System.out.println("exists = "+ exists); }}Copy the code

The results of

Get detailed information about the document

// Get the details of the document
	@Test
	public void GetDocument1(a) throws IOException{
		GetRequest getRequest = new GetRequest("fjj-index"."1");
		// Client execution
		GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
		// Print the contents of the document
		System.out.println(getResponse.getSourceAsString());
		// Output view
		System.out.println("getResponse = " + getResponse);

	}
Copy the code

Modify the document

// Modify the document information
	@Test
	public void UpdateDocument(a) throws IOException{
// Get updated information
		UpdateRequest updateRequest = new UpdateRequest("fjj-index"."1");
		// Set the response time
		updateRequest.timeout("1s");
		// Get the object
		User user = new User("Feng Jiaojiao".16."Female");
		// Convert to Json
		updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
		// Client execution
		UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
		// Print statusSystem.out.println(update.status()); }}Copy the code

The results of

Delete the document


	// Delete the document
	@Test
	public void DeleteDocument(a) throws IOException{
	// Get the request for the deleted document
		DeleteRequest deleteRequest = new DeleteRequest("fjj-index"."1");
		// Set the response time
		deleteRequest.timeout("1s");
		// Client execution
		DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
		System.out.println(delete.status());
	}
Copy the code

Above simple add delete check change end !!!!!!!!!!!!!!!!!! ,

Special batch add and fancy query

	// Add documents in batches
	@Test
	public void BulkRequest(a) throws IOException{
	// Get the batch add request
		BulkRequest bulkRequest = new BulkRequest();
		// Set the response time
		bulkRequest.timeout("10s");
		// Create a batch add collection
		ArrayList<User> list = new ArrayList<>();
		list.add(new User("f".13."nan"));
		list.add(new User("j1".13."nan"));
		list.add(new User("j2".13."nan"));
		list.add(new User("j3".13."nan"));
		/ / loop
		for (int i = 0; i <list.size() ; i++) {
			bulkRequest.add(
					new IndexRequest("fjj-index")
							.id(""+(i+1))
							.source(JSON.toJSONString(list.get(i)),XContentType.JSON));

		}
		// Client executionBulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT); System.out.println(bulk.hasFailures()); }}Copy the code

The results of

The query

	/ / query
	@Test
	public void testSearch(a) throws IOException{

	// Get the request for the query
		SearchRequest searchRequest = new SearchRequest("fjj-index");
		// Build criteria for search
		SearchSourceBuilder builder = new SearchSourceBuilder();
		// Query criteria can be implemented using the QueryBuilders tool
		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name"."j1");
		builder.query(termQueryBuilder);
		builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
		searchRequest.source(builder);
		// Client execution
		SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
		/ / output
		System.out.println(JSON.toJSONString(search.getHits()));
		for (SearchHit hit : search.getHits()) {
			System.out.println("hit = "+ hit); }}}Copy the code

The results of