欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Elasticsearch关于Java客户端的基本操作 (RestHighLevelClient)

程序员文章站 2022-07-01 16:06:58
...
@SpringBootTest
public class ESOpsDemoTest {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    AppcStatsExerciseHistoryMapper appcStatsExerciseHistoryMapper;

    @Test
    public void mainTest() throws IOException {
//        createIndex();
        getInfoById("stat","1");
//        dataToDoc();
    }

    /**
     * 创建索引
     */
    public void createIndex() throws IOException {
        AppcStatsExerciseHistory appcStatsExerciseHistory = appcStatsExerciseHistoryMapper.selectById(2);
        System.out.println("................"+appcStatsExerciseHistory.toString());
        IndexRequest indexRequest = new IndexRequest("stat").source(JSON.toJSONString(appcStatsExerciseHistory), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
//        IndexResponse[index=stat,type=_doc,id=HHzdX3kByQOrrywkSVI0,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
        System.out.println("indexResponse>>>>"+indexResponse.getResult().toString());
    }

    /**
     * 持久化数据,到doc里
     */
    @Test
    public void dataToDoc() throws IOException {
        List<AppcStatsExerciseHistory> allAppcStatsExerciseHistoryList = ChainWrappers.lambdaQueryChain(appcStatsExerciseHistoryMapper).list();
        BulkRequest bulkRequest = new BulkRequest();
//        AppcStatsExerciseHistory[] appcStatsExerciseHistorys = allAppcStatsExerciseHistoryList
//                .toArray(new AppcStatsExerciseHistory[allAppcStatsExerciseHistoryList.size()]);
//        bulkRequest.add(new IndexRequest("stat").source(XContentType.SMILE,appcStatsExerciseHistorys));
        for(AppcStatsExerciseHistory currAppcStatsExerciseHistory : allAppcStatsExerciseHistoryList){
            currAppcStatsExerciseHistory.setId(currAppcStatsExerciseHistory.getStatsHistoryId());
            bulkRequest.add(new IndexRequest("stat").source(JSON.toJSONString(currAppcStatsExerciseHistory), XContentType.JSON));
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("bulkResponse>>>"+ bulkResponse.toString());
    }


    public void getInfoById(String index,String id) throws IOException {
        GetRequest getRequest = new GetRequest(index,id);
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        System.out.println("sourceAsMap>>>>" + sourceAsMap.toString());
    }

参考资料 & 致谢