zoukankan      html  css  js  c++  java
  • Es基础api

    pom坐标 ,我安装的es是7.1.1 注意版本,同时注意要把 elasticsearch-rest-high-level-client 自带的

     org.elasticsearch 排包。重新引入 elasticsearch

    <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.1.1</version>
                <exclusions>
                    <exclusion>
                        <artifactId>elasticsearch</artifactId>
                        <groupId>org.elasticsearch</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.1.1</version>
            </dependency>

    附上完整的java代码

    package org.example.elasticsearch;
    
    import org.apache.http.HttpHost;
    import org.elasticsearch.action.ActionListener;
    import org.elasticsearch.action.DocWriteResponse;
    import org.elasticsearch.action.get.GetRequest;
    import org.elasticsearch.action.get.GetResponse;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.action.index.IndexResponse;
    import org.elasticsearch.action.search.SearchRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.action.update.UpdateRequest;
    import org.elasticsearch.action.update.UpdateResponse;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.index.query.*;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.builder.SearchSourceBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import java.io.IOException;
    import java.time.LocalDateTime;
    import java.util.HashMap;
    import java.util.Map;
    
    public class ElasticSearchTest {
    
        private RestHighLevelClient restHighLevelClient = null;
    
        // 在所有的测试方法之前执行
        @SuppressWarnings("resource")
        @Before
        public void init() throws Exception {
            restHighLevelClient = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("121.5.182.220", 9200, "http")));
    
        }
    
        @After
        public void destroy() throws Exception {
            restHighLevelClient.close();
        }
    
        @Test
        public void elasticsearchCreate() throws IOException {
            IndexRequest request = new IndexRequest("es_user");
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("user_name", "5t5");
            jsonMap.put("post_date", LocalDateTime.now());
            jsonMap.put("age", 23);
            jsonMap.put("gender", "male");
            jsonMap.put("height", 190);
            jsonMap.put("address", "shenyang tiexi gongrenchun");
            request.source(jsonMap);
            IndexResponse response = null;
            try {
                response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
                if(response.getResult().name().equalsIgnoreCase("created")){
                    System.out.println("insert index success");
                }else {
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Test
        public void elasticsearchUpdate() throws IOException {
            UpdateRequest updateRequest = new UpdateRequest("es_user","QDUw6XgBGWZZ4Vv4e9ID");
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("user_name", "kratos");
            jsonMap.put("post_date", LocalDateTime.now());
            jsonMap.put("age", 46);
            jsonMap.put("gender", "male");
            jsonMap.put("height", 195);
            jsonMap.put("address", "greece athens");
            updateRequest.doc(jsonMap);
            UpdateResponse response = null;
            try {
                response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
                if(response.getResult() == DocWriteResponse.Result.UPDATED){
                    System.out.println("updated index success");
                }else {
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Test
        public void testGetDoc() throws IOException {
            //查询请求对象
            GetRequest getRequest = new GetRequest("es_user","QDUw6XgBGWZZ4Vv4e9ID");
            GetResponse getResponse = restHighLevelClient.get(getRequest,RequestOptions.DEFAULT);
            //得到文档的内容
            Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
            System.out.println(sourceAsMap);
        }
    
        @Test
        public void testGetDocExist() throws IOException {
            //查询请求对象
            GetRequest getRequest = new GetRequest("es_user","QDUw6XgBGWZZ4Vv4e9ID");
            restHighLevelClient.existsAsync(getRequest,RequestOptions.DEFAULT, new ActionListener<Boolean>() {
    
                @Override
                public void onResponse(Boolean aBoolean) {
                //得到文档的内容
                    System.out.println(aBoolean);
                }
    
                @Override
                public void onFailure(Exception e) {
                    System.out.println(e);
                }
            });
    
        }
    
        @Test
        public void testQuery() {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.from(0);
            sourceBuilder.size(10);
            sourceBuilder.fetchSource(new String[]{"user_name"}, new String[]{});
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("address", "nanjing");
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("user_name", "snake");
    //        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime");
    //        rangeQueryBuilder.gte("2018-01-26T08:00:00Z");
    //        rangeQueryBuilder.lte("2018-01-26T20:00:00Z");
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            boolBuilder.must(matchQueryBuilder);
            boolBuilder.must(termQueryBuilder);
    //        boolBuilder.must(rangeQueryBuilder);
            sourceBuilder.query(boolBuilder);
            SearchRequest searchRequest = new SearchRequest("es_user");
    //        searchRequest.types(type);
            searchRequest.source(sourceBuilder);
            try {
                SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                SearchHit[] searchHtis = response.getHits().getHits();
                SearchHit searchHit = searchHtis[0];
                Map<String, Object> sourceResult = searchHit.getSourceAsMap();
                System.out.println(sourceResult.get("user_name"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    es中完整数据如下

    查询条件

    GET _search
    {
      "query": {
        "match": {
          "address": "nanjing"
        }
      }
    }
    {
      "took" : 5,
      "timed_out" : false,
      "_shards" : {
        "total" : 3,
        "successful" : 3,
        "skipped" : 0,
        "failed" : 0
      },
      "hits" : {
        "total" : {
          "value" : 1,
          "relation" : "eq"
        },
        "max_score" : 0.2876821,
        "hits" : [
          {
            "_index" : "es_user",
            "_type" : "_doc",
            "_id" : "QDUw6XgBGWZZ4Vv4e9ID",
            "_score" : 0.2876821,
            "_source" : {
              "address" : "nanjing honghua yingchunyuan",
              "gender" : "male",
              "user_name" : "snake",
              "post_date" : "2021-04-19T08:12:51.179Z",
              "age" : 23,
              "height" : 180
            }
          }
        ]
      }
    }
  • 相关阅读:
    ASP.NET缓存全解析(系列)
    updateprogress用法技巧
    text与img对齐
    9款Firefox插件提高设计开发效率
    ASP.NET页面实时进行GZIP压缩优化
    如何收缩和删除SQL日志文件
    闲扯加班
    与大家分享一点游戏管理晋升的心得(完整版)
    FDS (Flex Data Services)
    和我老婆去旅游
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14677645.html
Copyright © 2011-2022 走看看