Elasticsearch java简单增删改查

本文主要已window系统进行测试

首先去https://www.elastic.co/cn/downloads/elasticsearch下载ElasticSearch安装包

window的比较简单下载下来直接解压就可以使用了

解压后

双击执行 elasticsearch.bat,该脚本文件执行 ElasticSearch 安装程序,稍等片刻,打开浏览器,输入 http://localhost:9200 ,显式以下画面,说明ES安装成功

那接下来开始撸代码吧

新建个springboot工程 org.elasticsearch.client transport ${elasticsearch.version}

因为这是展示简单的用法所以结构比较简单,我先说下这几个类的作用吧

EsConfig读取es的配置文件主要包括集群名称ip和端口 SearchConfig 获取client对es进行crud操作 SearchController demo的控制层 UserService demo的业务逻辑

/**

  • Created by lwh
  • 读取es配置 */ @Component @PropertySource("classpath:es_config.properties") @Data public class EsConfig { @Value("{es.cluster.name}")  private String clusterName;//集群名称  @Value("{es.host.ip}") private String ip; @Value("${es.host.port}") private int port;

}

@Configuration public class SearchConfig {

@Autowired
EsConfig esConfig;

@Bean
public TransportClient client() throws UnknownHostException {
    TransportAddress node = new TransportAddress(
            InetAddress.getByName(esConfig.getIp()),
            esConfig.getPort()
    );
    Settings settings = Settings.builder()
            .put("cluster.name", esConfig.getClusterName())

            .build();
复制代码

/**

  • 配置忽略集群名校验。client.transport.ignore_cluster_name设置为 true
  • Settings settings = Settings.settingsBuilder()
  •                     .put("client.transport.sniff", true)
    复制代码
  •                     .put("client.transport.ignore_cluster_name", true)
    复制代码
  •                     .build();
    复制代码

*/ TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(node); return client; } }

@RestController public class SearchController {

@Autowired
private UserService userService;

@GetMapping("/get/user")
@ResponseBody
public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
    GetResponse response = userService.getById(id);

    if (!response.isExists()) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity(response.getSource(), HttpStatus.OK);
}

@PostMapping("add/user")
@ResponseBody
public ResponseEntity add(
        @RequestParam(name = "name") String name,
        @RequestParam(name = "age") int age,
        @RequestParam(name = "address") String address,
        @RequestParam(name = "mobile") String mobile
) {
    IndexResponse response;
    try {
        response = userService.add(name, age, address, mobile);
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity(response, HttpStatus.OK);
}


@DeleteMapping("remove/user")
public ResponseEntity remove(@RequestParam(name = "id") String id) {
    DeleteResponse response = userService.remove(id);

    return new ResponseEntity(response.getResult().toString(), HttpStatus.OK);
}

@PutMapping("modify/user")
@ResponseBody
public ResponseEntity modify(@RequestParam(name = "id") String id,
                             @RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "age", required = false) int age,
                             @RequestParam(name = "address", required = false) String address,
                             @RequestParam(name = "mobile", required = false) String mobile) {
    UpdateResponse response;
    try {
        response = userService.modify(id, name, age,address,mobile);
    } catch (Exception e) {
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity(response.getResult().toString(), HttpStatus.OK);
}
复制代码

}

@Service @Slf4j public class UserService {

private String indexName = "user"; //数据库名称
private String indexType = "test_es";    //数据表名称

@Autowired
private TransportClient client;

public GetResponse getById(String id) {
    return this.client.prepareGet(indexName, indexType, id).get();
}

public IndexResponse add(String name, Integer age, String address, String mobile) throws Exception {

    XContentBuilder content = XContentFactory.jsonBuilder()
            .startObject()
            .field("name", name)
            .field("age", age)
            .field("address", address)
            .field("mobile", mobile)
            .endObject();

    IndexResponse response = this.client.prepareIndex(indexName, indexType)
            .setSource(content)
            .get();

    return response;

}

public DeleteResponse remove(String id) {
    return this.client.prepareDelete(indexName, indexType, id).get();
}

public UpdateResponse modify(String id, String name, Integer age, String address, String mobile) throws Exception {
    UpdateRequest request = new UpdateRequest(indexName, indexType, id);

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

    if (name != null) {
        builder.field("name", name);
    }
    if (age != null) {
        builder.field("age", age);
    }
    if (address != null) {
        builder.field("address", address);
    }
    if (mobile != null) {
        builder.field("mobile", mobile);
    }
    builder.endObject();

    request.doc(builder);
    return this.client.update(request).get();
}
复制代码

}


demo地址 github.com/liweiheng/E…


转载于:https://juejin.im/post/5c74fbf6f265da2dc13c8d72

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值