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…

相關文章
相關標籤/搜索