ES7.9基本操作

2020-11-22  本文已影响0人  圆企鹅i
@Autowired

@Qualifier("restHighLevelClient")

private RestHighLevelClientclient;
@Test

public void addIndex() throws IOException{

    System.out.println(ESutils.INDEX);

    System.out.println(ESutils.ID);

  Brand brand =new Brand(1,"a","b");

  String s = JSON.toJSONString(brand);

    XContentBuilder builder =jsonBuilder()

            .startObject()

            .field("user", "kimchy")

            .field("postDate", new Date())

            .field("message", "trying out Elasticsearch")

            .endObject();

    XContentBuilder builder =jsonBuilder().field(s);

    String s1 = Strings.toString(builder);

    System.out.println("s1 = " + s1);

}

/**

*/

@Test

public void test0014Creat() throws IOException{

    // put testIndex  默认doc

    CreateIndexRequest request =new CreateIndexRequest("test_index");

    //执行请求                                        实现上面请求    默认参数

    CreateIndexResponse resp =client.indices().create(request, RequestOptions.DEFAULT);

    //

    System.out.println(resp);

  /* boolean test_index2 = elasticsearchTemplate.createIndex("test_index2");

        该版本好像还没有更新新的es

System.out.println("test_index2 = " + test_index2);*/

}
//exit + delete
@Test

public void test002Exit() throws IOException{

    // put testIndex  默认doc

    GetIndexRequest request =new GetIndexRequest("test_index3");

    boolean exists =client.indices().exists(request, RequestOptions.DEFAULT);

    System.out.println("exists = " + exists);

    DeleteIndexRequest deleteIndexRequest =new DeleteIndexRequest("test_index3");

    AcknowledgedResponse delete =client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);

    System.out.println("delete = " + delete.isAcknowledged());

}

/***

*文档操作

*/

//添加文档

@Test

public void test001Insert() throws IOException{

    User user =new User("a",12);

    //导向库

    IndexRequest request =new IndexRequest("test_index");

    //put test_index/_doc/1

//id

    request.id("1");

    //过期时间

    request.timeout("3s");

    //放入数据  设置数据格式

    request.source(JSON.toJSONString(user), XContentType.JSON);

    //用index 放入请求

    IndexResponse response =client.index(request, RequestOptions.DEFAULT);

    System.out.println("response = " + response);

    System.out.println(response.status());

    System.out.println(response.toString());

}

//获取信息

@Test

public void test002Get() throws IOException{

    //获取索引数据get test_index

    GetRequest request =new GetRequest("test_index", "1");

    // 不获取返回的_source 上下文

  /* request.fetchSourceContext(new FetchSourceContext(false));

request.storedFields("_none_");*/

    GetResponse documentFields =client.get(request, RequestOptions.DEFAULT);

    System.out.println(documentFields.toString());

    System.out.println(documentFields.getSourceAsMap());

}

//更新文档

@Test

public void test003Update() throws IOException{

    UpdateRequest updateRequest =new UpdateRequest("test_index", "1");

    User user =new User("B",2);

    updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

    UpdateResponse update =client.update(updateRequest, RequestOptions.DEFAULT);

    System.out.println(update.getResult());

    System.out.println(update);

}

/**

*/

//批量操作数据

@Test

public void test004bluk() throws IOException{

    BulkRequest bulkRequest =new BulkRequest();

    bulkRequest.timeout("10s");

    ArrayList<User> list =new ArrayList<>();

    list.add(new User("1a",2));

    list.add(new User("7a",3));

    list.add(new User("7a",6));

    list.add(new User("8a",9));

    list.add(new User("9a",12));

    list.add(new User("6a",22));

    list.add(new User("3a",32));

    list.add(new User("2a",42));

    list.add(new User("1a",52));

    for (int i =0; i

        bulkRequest.add(new IndexRequest(ESutils.INDEX)

                    .id((i+10)+"")

                    .source(JSON.toJSONString(list.get(i)),XContentType.JSON));

    }

    BulkResponse bulk =client.bulk(bulkRequest, RequestOptions.DEFAULT);

    System.out.println(bulk.hasFailures());

    System.out.println(bulk.buildFailureMessage());

    System.out.println(bulk.getItems());

    System.out.println(bulk.status());

    System.out.println(bulk.getTook());

    System.out.println(bulk.getIngestTook());

}

/**

*/

@Test

public void test001Search() throws IOException{

    //发起搜索请求

    SearchRequest searchRequest =new SearchRequest(ESutils.INDEX_GOODS);

    //搜索构建器

    SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

    //查询条件

    MatchQueryBuilder query1 = QueryBuilders.matchQuery("brandName", "三");

    RangeQueryBuilder query2 = QueryBuilders.rangeQuery("price").gte(1000).lte(2000);

    BoolQueryBuilder query = QueryBuilders.boolQuery().must(query2).must(query1);

    //设置搜索构造器参数

    searchSourceBuilder.from(0);

    searchSourceBuilder.size(5);

    searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.DESC));

    //添加高亮进入条件  使用高亮构造器

    searchSourceBuilder.highlighter(new HighlightBuilder().field("brandName").preTags("<p color = red >").postTags("<p>"));

    searchSourceBuilder.query(query).query(query);

    //搜索构造器参数加入搜索

    SearchRequest request = searchRequest.source(searchSourceBuilder);

    //老操作了 调用客户端search

    SearchResponse search =client.search(request, RequestOptions.DEFAULT);

    System.out.println(search.getHits());

    System.out.println("------------");

    search.getHits().forEach(s-> System.out.println(s));

    System.out.println("------------");

    System.out.println(search.getHits().getTotalHits());

    System.out.println("------------");

    //处理高亮之后

    for (SearchHit hit : search.getHits().getHits()) {

        Map<String, Object> sourceAsMap = hit.getSourceAsMap();

        //处理高亮字段

        Map<String, HighlightField> highlightFields = hit.getHighlightFields();

        HighlightField field = highlightFields.get("brandName");

        Text[] fragments = field.fragments();

        String a ="";

        for (Text fragment : fragments) {

            a+=fragment;

        }

        //高亮字段覆盖原字段

        sourceAsMap.put("brandName",a);

        System.out.println(sourceAsMap);

    }
上一篇 下一篇

猜你喜欢

热点阅读