Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add, delete, modify and check JAVA by ELASTICSEARCH

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you how ELASTICSEARCH to achieve the addition, deletion, modification and search of JAVA, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Object to manipulate ES: TransportClient org.elasticsearch.client transport ${elasticsearch.client.version}

My version is 5.4.0.

Create a TransportClient object

I injected it using spring's bean

@ SuppressWarnings ("resource") @ Bean (name= "transportClient") @ Lazypublic TransportClient getTransportClient () {TransportClient client= null; try {Settings settings= Settings.builder () .put ("cluster.name", "elasticsearch") .build (); client=new PreBuiltTransportClient (settings) .addTransportAddress (InetAddress.getByName ("192.168.0.11"), 9300); log.info ("es client object created successfully") } catch (Exception e) {log.error ("failed to create es client object"); log.error ("reason for failure:" + e.getMessage ()); System.exit (- 1);} return client;}

After the object is created successfully, it can be used to operate the es library. Its function is the same as spring-jdbctemplate,spring-jdbctemplate, which provides the function of adding, deleting, modifying and querying the database.

Spring also provides an object called Spring Data Elasticsearch to operate on es.

Reference documentation:

Http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa

I am using the object TransportClient provided by es itself.

Add data

The addition of data in es provides a variety of methods, which are somewhat similar to the hql language and are object-oriented.

Es supports batch operations, using batch objects in order to provide efficiency.

BulkRequestBuilder builder=transportClient.prepareBulk ()

There is one thing to note about the BulkRequestBuilder object. Because it is a batch operation, es ignores the incorrectness of the data, and even if your data is incorrect, builder will not report an error, so you need to ensure the accuracy of the data before operating with the object during debugging.

To insert data, you only need to convert your object to json, and then insert it in batch.

@ Overridepublic void batchAddMyZu (List list) {BulkRequestBuilder builder=transportClient.prepareBulk (); for (Family family:list) {String objstr= JSON.toJSONString (family); builder.add (client.prepareIndex ("family", "myfamily", family.getPrimaryKey ()) .setSource (objstr, XContentType.JSON));} builder.execute (). ActionGet (); System.out.println ("the number of data inserted this time is" + list.size ());}

Various insertion types can be specified in the setSource method, which I usually use in json format.

Delete operation

Es can delete data by specifying index,type,id, and it also supports search to delete deleteByQuery

Delete method by specifying id

@ Overridepublic void batchUndercarriageFamilies (List publishIds) {BulkRequestBuilder builder=transportClient.prepareBulk (); for (String publishId:publishIds) {builder.add (transportClient.prepareDelete (FAMILY, FAMILY_MARKETFAMILY, publishId). Request ();} builder.get ();}

Delete via deleteByQuery

@ Overridepublic void delMyZu (String guid, String userId) {DeleteByQueryAction.INSTANCE.newRequestBuilder (transportClient) .source (FAMILY) .filter (QueryBuilders.boolQuery () .must (QueryBuilders.termQuery ("zuGUID", guid)) .must (QueryBuilders.termQuery ("userId", userId)) .must (QueryBuilders.typeQuery (FAMILY_MYFAMILY)) .get ();}

The QueryBuilder object can make any query

Modify operation

I now modify the sauce sample of the specified field according to the specified index.

@ Overridepublic void updateMyZu_Related4MyZuValue (List list) {BulkRequestBuilder builder=transportClient.prepareBulk (); for (Related4MyZuValue value:list) {try {XContentBuilder source=XContentFactory.jsonBuilder () .startObject () .field ("related4ZuValue", value.getRelated4ZuValue ()) .field ("zuSalePrice", value.getZuSalePrice ()) .endObject () Builder.add (transportClient.prepareUpdate (FAMILY, FAMILY_MYFAMILY, value.getPrimaryKey ()) .setDoc (source));} catch (IOException e) {continue;}} builder.get ();}

My operation is to modify the value of related4ZuValue and zuSalePrice of the data after executing id.

Query operation

The main function of es is to query.

QueryBuilder is the object that sets query conditions. You can set various conditions through it.

Post a few at random and feel it for yourself.

BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery (); if (keywordwords). Keyword) {QueryBuilder nameBuilder=QueryBuilders.matchQuery ("zuName", keyword) .questions ("ik_max_word") .boost (10); QueryBuilder labelBuilder=QueryBuilders.matchQuery ("zuLabelName", keyword) .requests ("ik_max_word"). Boost (10); QueryBuilder categoryBuilder=QueryBuilders.matchQuery ("categoryName", keyword) .requests ("ik_max_word") .boost (10); boolQueryBuilder.should (nameBuilder). Should (labelBuilder) .should (categoryBuilder) } else {boolQueryBuilder.must (QueryBuilders.matchAllQuery ());} SearchResponse response=transportClient.prepareSearch (FAMILY) .setTypes (FAMILY_MARKETFAMILY) .setQuery (boolQueryBuilder) .setFrom ((page-1) * pageSize) .setSize (pageSize) .setExplain (true) .get (); SearchHits hits=response.getHits (); BoolQueryBuilder builders=new BoolQueryBuilder (); / / add conditional builders.must (QueryBuilders.termQuery ("userId", userId)) If (relatedValue==RelatedValue.MyBuyerZu.value ()) {builders.must (QueryBuilders.nestedQuery ("related4ZuValue", QueryBuilders.boolQuery (). Must (QueryBuilders.termQuery ("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue (relatedValue) / / .must (QueryBuilders.rangeQuery ("endTime") .lte (LongformStringDate (System.currentTimeMillis (), ScoreMode.None) } else {builders.must (QueryBuilders.nestedQuery ("related4ZuValue", QueryBuilders.termQuery ("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue (relatedValue)), ScoreMode.None));} SearchResponse response=transportClient.prepareSearch (FAMILY) .setTypes (FAMILY_MYFAMILY) .setQuery (builders). SetFrom ((page-1) * pageSize) .setSize (pageSize) .get (); SearchHits hits=response.getHits (); @ Overridepublic MarketFamily getMarketFamily (String guid) {MarketFamily marketFamily=new MarketFamily () SearchResponse response=transportClient.prepareSearch (FAMILY) .setTypes (FAMILY_MYFAMILY) .setQuery (QueryBuilders.termQuery ("zuGUID", guid)) .setSize (1) .get (); SearchHits hits=response.getHits (); for (SearchHit hit:hits.getHits ()) {marketFamily=JSON.parseObject (hit.getSourceAsString (), MarketFamily.class);} return marketFamily;} take the sum of query results count@Overridepublic long countMyAllZu (String userId, int relatedValue) {BoolQueryBuilder builders=new BoolQueryBuilder () Builders.must (QueryBuilders.termQuery ("userId", userId)) If (relatedValue==RelatedValue.MyBuyerZu.value ()) {builders.must (QueryBuilders.nestedQuery ("related4ZuValue", QueryBuilders.boolQuery (). Must (QueryBuilders.termQuery ("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue (relatedValue) .must (QueryBuilders.rangeQuery ("endTime") .lte (LongformStringDate (System.currentTimeMillis (), ScoreMode.None) } else {builders.must (QueryBuilders.nestedQuery ("related4ZuValue", QueryBuilders.termQuery ("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue (relatedValue)), ScoreMode.None);} SearchResponse response=transportClient.prepareSearch (FAMILY) .setTypes (FAMILY_MYFAMILY) .setQuery (builders) .setSize (1) .get (); SearchHits hits=response.getHits (); return hits.getTotalHits () } aggregate summation sum@Overridepublic long getPlatformZuOrdersTotalAmount (String keyword,String startTime,String endTime) {BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery (); if (keyword==null | | keyword.equals (")) {QueryBuilder queryBuilder=QueryBuilders.matchAllQuery (); boolQueryBuilder.must (queryBuilder);} else {QueryBuilder zuNameBuilder=QueryBuilders.matchQuery (" zuName ", keyword); QueryBuilder buyerNameBuilder=QueryBuilders.matchQuery (" buyerName ", keyword); QueryBuilder sellerNameBuilder=QueryBuilders.matchQuery (" sellerName ", keyword); boolQueryBuilder.should (zuNameBuilder) .should (buyerNameBuilder) .should (sellerNameBuilder) } if (! startTime.equals (")) {QueryBuilder addTimeBuilder=QueryBuilders.rangeQuery (" addTime ") .from (startTime) .to (endTime); boolQueryBuilder.must (addTimeBuilder);} SearchResponse response=transportClient.prepareSearch (FAMILY) .setTypes (FAMILY_FAMILYORDER) .setQuery (boolQueryBuilder) .addAggregation (AggregationBuilders.sum (" price "). Field (" price ") .get (); Sum sum=response.getAggregations (). Get (" price ") Return (long) sum.getValue ();} these are all the contents of the article "how to add, delete, modify and query JAVA in ELASTICSEARCH". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report