SoFunction
Updated on 2025-03-03

About Elasticsearch encapsulation of public indexes and adding, deleting, modifying and searching

What is index?

  • definition: Index is the logical namespace used in Elasticsearch to store data. It consists of multiple documents, each of which is structured data in JSON format
  • Corresponding relationship: In relational databases, indexes are similar to tables; in Elasticsearch, indexes are equivalent to collections or directories of databases.

rely

Choose a plan one

If you use this dependency, you must use it with the configuration class

 <!-- elasticsearch -->
            <dependency>
                <groupId></groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.7.0</version>
            </dependency>
            <dependency>
                <groupId></groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.7.0</version>
            </dependency>

Choice plan two

If you use this dependency, the configuration class can be written or not, because the springboot project has helped us automatically complete the configuration and we don't need to write it ourselves.

 <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

Configuration

es:
  host: 111.229.0.43
  port: 9200
  scheme: http

Configuration class

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Data
@Component
public class InitEsRes {

    @Value("${}")
    private String host;
    @Value("${}")
    private int port;
    @Value("${}")
    private String scheme;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                (new HttpHost(host,port,scheme))
        );
    }
}

dto

package ;

import ;
import ;
import ;
import ;

/**
  * @Author: xsp
  * @Description: es index transfer object
  * @name: EsIndexDto
  * @Date: 2024/10/16 15:30
  */
@Data
public class EsIndexDto {
    /**
      * Index name
      */
    @NotEmpty(message = "The index name cannot be empty")
    @ApiModelProperty(value = "Index Name", required = true, example = "。。。。")
    private String indexName;
    /**
      * Index Mapping
      */
    @ApiModelProperty(value = "Index Mapping", required = true, example = "。。。。")
    private String indexMappings;
    /**
      * Index configuration
      */
    @ApiModelProperty(value = "Index Configuration", required = true, example = "。。。。")
    private String indexSettings;

}

controller

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .*;

import ;

/**
  * @Author: xsp
  * @Description: es index management
  * @name: EsController
  * @Date: 2024/10/15 20:38
  */
@RestController
@RequestMapping("/index")
@Validated
@Api(tags = "es index management")
public class EsIndexController {
    @Autowired
    private EsIndexService esIndexService;

    /**
      * The interface to create indexes
      * @param esIndexDto Index Information
      * @return
      */
    @ApiOperation(value = "Create an index")
    @PostMapping("/create")
    public CommonResult createIndex(@Validated @RequestBody EsIndexDto esIndexDto) {
         (esIndexDto);
        return ("Index creation successfully"); // Call service method to create index    }
    /**
      * Delete the indexed interface
      * @param indexName Index name
      * @return
      */
    @ApiOperation(value = "Delete index")
    @DeleteMapping("/delete")
    public CommonResult deleteIndex(@RequestParam @NotEmpty(message = "The index name cannot be empty") String indexName) {
        (indexName); // Call the service method to delete the index        return ("Index deletion successfully");
    }

    /**
      * The interface to obtain the index
      * @param indexName Index name
      * @return
      */
    @ApiOperation(value = "Get index map")
    @GetMapping("/get")
    public CommonResult&lt;Map&lt;String, Object&gt;&gt; getIndex(@RequestParam  @NotEmpty(message = "The index name cannot be empty") String indexName) {
        Map&lt;String, Object&gt; indexMappings = (indexName);
        return (indexMappings); // Call service method to get index    }


    /**
      * Modify the index configuration according to the index name
      * @param esIndexDto Index Information
      * @return
      */
    @ApiOperation(value = "Modify index configuration")
    @PutMapping("/update")
    public CommonResult updateIndex(@Validated @RequestBody EsIndexDto esIndexDto) {
        (esIndexDto);
        return ("Index update successfully"); // Call service method to update the index    }
    /**
      * Determine whether the index exists
      * @param indexName Index name
      * @return
      */
    @ApiOperation(value = "Judge whether the index exists")
    @GetMapping("/exists")
    public CommonResult exists(@RequestParam  @NotEmpty(message = "The index name cannot be empty") String indexName) {
        boolean exists =(indexName);
        return (exists);
    }
}

serveice

package ;

import ;
import ;

import ;
import ;

/**
 * @Author:xsp
 * @Description:
 * @name:EsService
 * @Date:2024/10/15 20:39
 */
public interface EsDocService {
    /**
      * Add in batches
      * @param esDocDto Document Information
      */
    void batchAdd(EsDocDto esDocDto);

    /**
      * Batch deletion
      * @param indexName Index name
      * @param ids Multiple ids
      */
    void batchDelete(String indexName,  List&lt;String&gt; ids);
}

impl

package ;

import ;
import ;
import ;
import .log4j.Log4j2;
import .slf4j.Slf4j;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

/**
 * @Author:xsp
 * @Description:
 * @name:EsServiceImpl
 * @Date:2024/10/15 20:39
 */
@Service
@Slf4j
public class EsIndexServiceImpl implements EsIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
      * Create an index
      *
      * @param esIndexDto Index Information
      */
    @Override
    public void createIndex(EsIndexDto esIndexDto) {
        // Check whether the index already exists        if (exists(())) {
            throw new RuntimeException("The index already exists: " + ());
        }

        // Create index request        CreateIndexRequest request = new CreateIndexRequest(());

        // Set index configuration        if ((())) {
            ((), );
        }

        // Perform the index creation operation        try {
            ().create(request, );
            ("Index creation successfully: {}", ());
        } catch (Exception e) {
            ("Failed to create index, error message: {}", ());
            throw new RuntimeException("Index creation failed: " + (), e);
        }
    }

    /**
      * Delete the index
      *
      * @param indexName Index name
      */
    @Override
    public void deleteIndex(String indexName) {
        // Check whether the index exists        if (!exists(indexName)) {
            throw new RuntimeException("The index does not exist: " + indexName);
        }

        // Create a delete index request        DeleteIndexRequest request = new DeleteIndexRequest(indexName);

        // Perform the delete index operation        try {
            ().delete(request, );
            ("Index deletion successfully: {}", indexName);
        } catch (Exception e) {
            ("Failed to delete index, error message: {}", ());
            throw new RuntimeException("Delete index failed: " + indexName, e);
        }
    }

    /**
      * Get index map
      *
      * @param indexName Index name
      * @return Index mapping information
      */
    @Override
    public Map&lt;String, Object&gt; getIndex(String indexName) {
        // Check whether the index exists        if (!exists(indexName)) {
            throw new RuntimeException("The index does not exist: " + indexName);
        }

        // Create a get index request        GetIndexRequest request = new GetIndexRequest(indexName);

        // Perform the acquisition index mapping operation        try {
            GetIndexResponse response = ().get(request, );
            ("Get index map successfully: {}", indexName);
            return ().get(indexName).sourceAsMap(); // Return to index map        } catch (Exception e) {
            ("Failed to get index map, error message: {}", ());
            throw new RuntimeException("Failed to get index map: " + indexName, e);
        }
    }

    /**
      * Update index configuration
      *
      * @param esIndexDto Index Information
      */
    @Override
    public void updateIndex(EsIndexDto esIndexDto) {
        // Check whether the index exists        if (!exists(())) {
            throw new RuntimeException("The index does not exist: " + ());
        }

        // Create an update index setting request        UpdateSettingsRequest request = new UpdateSettingsRequest(());

        // Update index map        if ((())) {
            ((), );
        }

        // Perform update index setting operation        try {
            boolean acknowledged = ().putSettings(request, ).isAcknowledged();
            if (acknowledged) {
                ("Index settings are updated successfully: {}", ());
            } else {
                ("Index settings update not confirmed: {}", ());
            }
        } catch (Exception e) {
            ("Failed to update index settings, error message: {}", ());
            throw new RuntimeException("Update index settings failed: " + (), e);
        }
    }

    /**
      * Determine whether the index exists
      *
      * @param indexName Index name
      * @return Does the index exist
      */
    @Override
    public boolean exists(String indexName) {
        // Create a get index request        GetIndexRequest request = new GetIndexRequest(indexName);
        try {
            // Perform the access to index and return whether the index exists            boolean exists = ().exists(request, );
            ("Determine whether the index exists: {}, result: {}", indexName, exists);
            return exists;
        } catch (Exception e) {
            ("Determine whether the index exists失败, error message: {}", ());
            return false; // Return to judgment failed        }
    }


}

Unified result set

package ;

import ;

/**
  * General return object
  * Created by 9a8204a7-f77d-4ab8-ae70-b4721fef2f95 on 2019/4/19.
  */
public class CommonResult&lt;T&gt; {
    private long code;
    private String message;
    private T data;

    protected CommonResult() {
    }

    protected CommonResult(long code, String message, T data) {
         = code;
         = message;
         = data;
    }

    /**
      * Successfully returned information
      * @param message prompt message
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; successMessage(String message) {
        return new CommonResult&lt;T&gt;((), message, null);
    }
    /**
      * Result successfully
      *
      * @param data obtained data
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; success(T data) {
        return new CommonResult&lt;T&gt;((), (), data);
    }

    /**
      * Result successfully
      *
      * @param data obtained data
      * @param message prompt message
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; success(T data, String message) {
        return new CommonResult&lt;T&gt;((), message, data);
    }


    /**
      * Failed to return result
      * @param errorCode error code
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; failed(IErrorCode errorCode) {
        return new CommonResult&lt;T&gt;((), (), null);
    }

    /**
      * Failed to return result
      * @param errorCode error code
      * @param message Error message
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; failed(IErrorCode errorCode,String message) {
        return new CommonResult&lt;T&gt;((), message, null);
    }

    /**
      * Failed to return result
      * @param message prompt message
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; failed(String message) {
        return new CommonResult&lt;T&gt;((), message, null);
    }

    /**
      * Failed to return result
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; failed() {
        return failed();
    }

    /**
      * Parameter verification failed to return result
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; validateFailed() {
        return failed(ResultCode.VALIDATE_FAILED);
    }

    /**
      * Parameter verification failed to return result
      * @param message prompt message
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; validateFailed(String message) {
        return new CommonResult&lt;T&gt;(ResultCode.VALIDATE_FAILED.getCode(), message, null);
    }

    /**
      * Not logged in to return results
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; unauthorized(T data) {
        return new CommonResult&lt;T&gt;((), (), data);
    }

    /**
      * Unauthorized return result
      */
    public static &lt;T&gt; CommonResult&lt;T&gt; forbidden(T data) {
        return new CommonResult&lt;T&gt;((), (), data);
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
         = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
         = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
         = data;
    }

    @Override
    public String toString() {
        return (this);
    }
}

Here I am using this unified result set, and use the corresponding unified result set based on my actual situation.

Spring native validation abnormality

    @ResponseBody
    @ExceptionHandler(value = )
    public CommonResult handle(ApiException e) {
        if (() != null) {
            return (());
        }
        return (());
    }

    @ResponseBody
    @ExceptionHandler(value = )
    public CommonResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = ();
        String message = null;
        if (()) {
            FieldError fieldError = ();
            if (fieldError != null) {
                message = ()+();
            }
        }
        return (message);
    }

    @ResponseBody
    @ExceptionHandler(value = )
    public CommonResult handleValidException(BindException e) {
        BindingResult bindingResult = ();
        String message = null;
        if (()) {
            FieldError fieldError = ();
            if (fieldError != null) {
                message = ()+();
            }
        }
        return (message);
    }

    /**
      * Maximum exception
      * @param e
      * @return
      */
    @ResponseBody
    @ExceptionHandler(value = )
    public CommonResult handle(Exception e) {
        ();
        return (());
    }

Here I am using these exception catchers written by them, and use the corresponding exception catch based on my actual situation.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.