Elasticsearch java简单增删改查

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

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

window的比较简单下载下来直接解压就能够使用了github

解压后spring

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

那接下来开始撸代码吧json

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

由于这是展现简单的用法因此结构比较简单,我先说下这几个类的做用吧springboot

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

/**elasticsearch

  • 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…

相关文章
相关标签/搜索