elasticsearch 的增删改查 json和springboot

时间:2019-01-10
本文章向大家介绍elasticsearch 的增删改查 json和springboot,主要包括elasticsearch 的增删改查 json和springboot使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先是json直接的增删该查,在Postman里直接通过Json语句修改ES里的索引

POST 127.0.0.1:9200/people


{
    "settings":{
        "number_of_shards": 3,
        "number_of_replicas": 1
    },
    "mappings":{
        "man":{
            "properties":{
                "name":{
                    "type":"text"
                },
                "country":{
                    "type":"keyword"
                },
                "age":{
                    "type":"integer"
                },
                "date":{
                    "type":"date",
                    "format":"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
                }
            }
        }
    }
}

增加一行:

'PUT 127.0.0.1:9200/people/man/1 

{
    "name" : astronaut
    "country" : China
    "age":20
    "date" : 1998-03-20
}

更新:

POST 127.0.0.1:9200/people/man/1/_update

方法1:

{
    "script":{
        "lang":"painless",
        "inline":"ctx._source.age += 10"
    }
}

方法2:

{
    "script":{
        "lang":"painless",
        "inline":"ctx._source.age = params.age",
        "params":{
            "age":100
        }
    }
}

删除一行数据:

DELETE   127.0.0.1:9200/people/man/1

查找:

POST 127.0.0.1:9200/people/_search

{
    "query":{
        "match_all":{}
    }
}
{
    "query":{
        "match":{
            "name":"astronaut"
        }
    }
}
{
    "aggs":{
        "group_by_age":{
            "terms":{
                "field":"age"
            }
        }
    }
}

 

 

springboot中elasticsearch api的使用:

首先先配置连接:

@Configuration
public class MyConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {

        TransportAddress node = new TransportAddress(
                InetAddress.getByName("localhost"),  
                9300);    //elasticsearch的tcp接口

        Settings settings = Settings.builder()
                .put("cluster.name","astronaut's cluster")
                .build();

        TransportClient client =  new PreBuiltTransportClient(settings);
        client.addTransportAddress(node); //如果需要多个节点,直接new node,然后add


        return client;
    }
}

之后,在controller中实现增删改查:

得到一条数据:

    @GetMapping("/get/people/man")   //localhost:8080/get/people/man?id=1
    @ResponseBody
    public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
        if (id.isEmpty()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        GetResponse result = this.client.prepareGet("people", "man", id)
                .get();

        if (!result.isExists()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }

增加一条数据:

   @PostMapping("/add/people/man")
    @ResponseBody
    public ResponseEntity add(
            @RequestParam(name = "name") String name,
            @RequestParam(name = "country") String country,
            @RequestParam(name = "age") String age,
            @RequestParam(name = "date")
            @DateTimeFormat(pattern = "yyyy-MM-dd")
                    Date date
    ) {
        try {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name", name)
                    .field("country", country)
                    .field("age", age)
                    .field("date", date.getTime())
                    .endObject();


            IndexResponse result = this.client.prepareIndex("people", "man")
                    .setSource(content)
                    .get();


            return new ResponseEntity(result.getId(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }


    }

删除:

    @DeleteMapping("/delete/people/man")
    @ResponseBody
    public ResponseEntity delete(@RequestParam(name = "id") String id) {
        if (id.isEmpty()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        DeleteResponse result = this.client.prepareDelete("people", "man", id).get();
        return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
    }

更新:

   @PutMapping("/update/people/man")
    @ResponseBody
    public ResponseEntity update(@RequestParam(name = "id") String id
            , @RequestParam(name = "name", required = false) String name
            , @RequestParam(name = "country", required = false) String country
            , @RequestParam(name = "age", required = false) String age
                                 //, @RequestParam(name = "date", required = false) Date date
    ) {
        UpdateRequest update = new UpdateRequest("people", "man", id);

        try {
            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();

            if (name != null) {
                builder.field("name", name);
            }
            if (country != null) {
                builder.field("country", country);
            }
            if (age != null) {
                builder.field("age", age);
            }
//            if(date!=null){
//                builder.field("date", date.getTime());
//            }

            builder.endObject();

            update.doc(builder);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        try {
            UpdateResponse result = this.client.update(update).get();
            return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

查找(直接查找和范围查找):

    @PostMapping("/query/people/man")
    @ResponseBody
    public ResponseEntity query(@RequestParam(name = "name", required = false) String name,
                                @RequestParam(name = "country", required = false) String country,
                                @RequestParam(name = "gt_age", defaultValue = "0") int gtage,
                                @RequestParam(name = "lt_age", required = false) Integer ltage) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (name != null) {
            boolQuery.must(QueryBuilders.matchQuery("name", name));
        }
        if (country != null) {
            boolQuery.must(QueryBuilders.matchQuery("country", country));
        }

        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age")
                .from(gtage);
        if (ltage != null && ltage > 0) {
            rangeQuery.to(ltage);
        }

        boolQuery.filter(rangeQuery);

        SearchRequestBuilder builder = this.client.prepareSearch("people")
                .setTypes("man")
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10);

        System.out.println(builder);

        SearchResponse response = builder.get();
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        for(SearchHit hit : response.getHits()){
            result.add(hit.getSourceAsMap());
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }