This article source: making here | | GitEE, click here

A brief introduction to the basic API

1, RestHighLevelClient

ResHighLevelClient API is a recommended client component of ElasticSearch. It encapsulates the methods of operating ES, including index structure management, data add, delete, update and search management, common query methods, and can be combined with native ES query syntax, which is very powerful.

When using the syntax of ResHighLevelClient, there are several aspects mentioned above. After mastering the basic usage, some customization encapsulation can be done according to the business characteristics, so that the business needs can be solved more elegantly.

2. Core dependencies

Using ResHighLevelClient requires a dependency on the REST-high-level-client package and the underlying dependencies associated with ES.

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

Second, index management

There is no need to update the index because of the data structure of ES. New fields can be written directly when the data is updated. There is no need to update the index structure in advance.

@Service public class EsIndexOperation { @Resource private RestHighLevelClient client ; private final RequestOptions options = RequestOptions.DEFAULT; /** * Check if index exists */ public Boolean checkIndex (String index) {try {return client.indices().exists(new) GetIndexRequest(index), options); } catch (IOException e) { e.printStackTrace(); } return Boolean.FALSE ; } public Boolean createIndex (String indexName,Map<String, Object bb0 ColumnMap){try {if(! checkIndex(indexName)){ CreateIndexRequest request = new CreateIndexRequest(indexName); if (columnMap ! = null && columnMap.size()>0) { Map<String, Object> source = new HashMap<>(); source.put("properties", columnMap); request.mapping(source); } this.client.indices().create(request, options); return Boolean.TRUE ; } } catch (IOException e) { e.printStackTrace(); } return Boolean.FALSE; } /** * drop index */ public Boolean deleteIndex(String IndexName){try {if(Checkindex (IndexName)){deleteIndexRequest request = new DeleteIndexRequest(indexName); AcknowledgedResponse response = client.indices().delete(request, options); return response.isAcknowledged(); } } catch (Exception e) { e.printStackTrace(); } return Boolean.FALSE; }}

Three, data management

Here, when you update the data, you can modify the index structure directly by putting new fields in the DataMap.

@Service public class EsDataOperation { @Resource private RestHighLevelClient client ; private final RequestOptions options = RequestOptions.DEFAULT; Public Boolean insert (String indexName, String indexName, String indexName) Map<String,Object> dataMap){ try { BulkRequest request = new BulkRequest(); request.add(new IndexRequest(indexName,"doc").id(dataMap.remove("id").toString()) .opType("create").source(dataMap,XContentType.JSON)); this.client.bulk(request, options); return Boolean.TRUE ; } catch (Exception e){ e.printStackTrace(); } return Boolean.FALSE; } /** ** * Serve (String indexName, String indexName, String indexName) List<Map<String,Object>> userIndexList){ try { BulkRequest request = new BulkRequest(); for (Map<String,Object> dataMap:userIndexList){ request.add(new IndexRequest(indexName,"doc").id(dataMap.remove("id").toString()) .opType("create").source(dataMap,XContentType.JSON)); } this.client.bulk(request, options); return Boolean.TRUE ; } catch (Exception e){ e.printStackTrace(); } return Boolean.FALSE; } /** * update data, */ public Boolean update (String indexName, String indexName, String indexName, String indexName, String indexName) Map<String,Object> dataMap){ try { UpdateRequest updateRequest = new UpdateRequest(indexName,"doc", dataMap.remove("id").toString()); updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); updateRequest.doc(dataMap) ; this.client.update(updateRequest, options); return Boolean.TRUE ; } catch (Exception e){ e.printStackTrace(); } return Boolean.FALSE; } public Boolean delete (String indexName, String indexName, String indexName, String indexName); String id){ try { DeleteRequest deleteRequest = new DeleteRequest(indexName,"doc", id); this.client.delete(deleteRequest, options); return Boolean.TRUE ; } catch (Exception e){ e.printStackTrace(); } return Boolean.FALSE; }}

Four, query operation

Note: CountRequest syntax for query totals, data conversion syntax for SearchRequest query results, offset location and page size need to be specified in paging query.

@Service public class EsQueryOperation { @Resource private RestHighLevelClient client ; private final RequestOptions options = RequestOptions.DEFAULT; Public Long Count (String IndexName){public Long Count (String IndexName){public Long Count (String IndexName){public Long Count (String IndexName);  queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L)); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(queryBuilder); CountRequest countRequest = new CountRequest(indexName); countRequest.source(sourceBuilder); try { CountResponse countResponse = client.count(countRequest, options); return countResponse.getCount(); } catch (Exception e) { e.printStackTrace(); } return 0L; } /** * SearchSourceBuilder */ public List<Map<String,Object BB0 > List (String IndexName) {// SearchSourceBuilder = SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L)); QueryBuilders. Mustnot (queryBuilders. TermQuery (" Name "," Beijing - Li 4 ")); sourceBuilder.query(queryBuilder); SearchRequest searchRequest = new SearchRequest(indexName); searchRequest.source(sourceBuilder); try { SearchResponse searchResp = client.search(searchRequest, options); List<Map<String,Object>> data = new ArrayList<>() ; SearchHit[] searchHitArr = searchResp.getHits().getHits(); for (SearchHit searchHit:searchHitArr){ Map<String,Object> temp = searchHit.getSourceAsMap(); temp.put("id",searchHit.getId()) ; data.add(temp); } return data; } catch (Exception e) { e.printStackTrace(); } return null ; } public List<Map<String,Object>> page (String indexName,Integer Offset,Integer Size) {// SearchSourceBuilder SourceBuilder = new SearchSourceBuilder(); sourceBuilder.from(offset); sourceBuilder.size(size); sourceBuilder.sort("createTime", SortOrder.DESC); SearchRequest searchRequest = new SearchRequest(indexName); searchRequest.source(sourceBuilder); try { SearchResponse searchResp = client.search(searchRequest, options); List<Map<String,Object>> data = new ArrayList<>() ; SearchHit[] searchHitArr = searchResp.getHits().getHits(); for (SearchHit searchHit:searchHitArr){ Map<String,Object> temp = searchHit.getSourceAsMap(); temp.put("id",searchHit.getId()) ; data.add(temp); } return data; } catch (Exception e) { e.printStackTrace(); } return null ; }}

Five, the sorting method

In addition to the normal ascending and descending rules for specified fields, you can also make certain data sink or top based on custom sorting rules based on native scripting syntax.

@Service public class EsSortOperation { @Resource private RestHighLevelClient client ; private final RequestOptions options = RequestOptions.DEFAULT; Public List<Map<String,Object bb0 > sort (String indexName) { SearchSourceBuilder SourceBuilder = new SearchSourceBuilder(); sourceBuilder.sort("createTime", SortOrder.ASC); sourceBuilder.sort("age",SortOrder.DESC) ; SearchRequest searchRequest = new SearchRequest(indexName); searchRequest.source(sourceBuilder); try { SearchResponse searchResp = client.search(searchRequest, options); List<Map<String,Object>> data = new ArrayList<>() ; SearchHit[] searchHitArr = searchResp.getHits().getHits(); for (SearchHit searchHit:searchHitArr){ Map<String,Object> temp = searchHit.getSourceAsMap(); temp.put("id",searchHit.getId()) ; data.add(temp); } return data; } catch (Exception e) { e.printStackTrace(); } return null ; } /** * Sort */ public List<Map<String,Object>> defSort (String indexName) {// Sort [age 12-->60]\[age 19-- -->10]\[age 13-->30]\[age 18-->40],age 1 Script = new Script("def _ageSort = doc['age']. 60:" + "(doc['age'].value == 19? 10:" + "(doc['age'].value == 13? 30:" + "(doc['age'].value == 18? 40:1)));" + "_ageSort;" ); ScriptSortBuilder sortBuilder = SortBuilders.scriptSort(script,ScriptSortBuilder.ScriptSortType.NUMBER); sortBuilder.order(SortOrder.ASC); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.sort(sortBuilder); SearchRequest searchRequest = new SearchRequest(indexName); searchRequest.source(sourceBuilder); try { SearchResponse searchResp = client.search(searchRequest, options); List<Map<String,Object>> data = new ArrayList<>() ; SearchHit[] searchHitArr = searchResp.getHits().getHits(); for (SearchHit searchHit:searchHitArr){ Map<String,Object> temp = searchHit.getSourceAsMap(); temp.put("id",searchHit.getId()) ; data.add(temp); } return data; } catch (Exception e) { e.printStackTrace(); } return null ; }}

Six, the source code address

Making address GitEE, https://github.com/cicadasmile/data-manage-parent, https://gitee.com/cicadasmile/data-manage-parent

Recommended reading: Programming system reorganization

The serial number The project name Making the address GitEE address Recommend index
01 Java describes design patterns, algorithms, and data structures Making, click here GitEE, click here Being fostered fostered fostered fostered
02 Java Foundation, Concurrency, Object-oriented, Web Development Making, click here GitEE, click here Being fostered fostered fostered
03 SpringCloud microservice base component case detail Making, click here GitEE, click here Do do do
04 SpringCloud microservice architecture practical comprehensive case Making, click here GitEE, click here Being fostered fostered fostered fostered
05 Getting started with the SpringBoot Framework basics Making, click here GitEE, click here Being fostered fostered fostered
06 SpringBoot framework integrates common middleware development Making, click here GitEE, click here Being fostered fostered fostered fostered
07 Basic cases of data management, distribution, architecture design Making, click here GitEE, click here Being fostered fostered fostered fostered
08 Big data series, storage, components, computing and other frameworks Making, click here GitEE, click here Being fostered fostered fostered fostered