内网5.4.1版本比较低,不支持外网的7.13.2的api调用,只能直接通过curl请求来操作。
首先创建索引,可以直接创建,删除,不过一般都是需要mappings和settings,所以创建的时候需要指定。
public boolean addEsIndex(String indexName){RestTemplate restTemplate = new RestTemplate();String ESurl = "http://localhost:9200/" + indexName;JSONObject body = getProperties();ResponseEntity<String> exchange = null;try{HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.setContentType(MediaType.APPLICATION_JSON);HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(body, httpHeaders);exchange = restTemplate.exchange(ESurl, HttpMethod.PUT, mapHttpEntity, String.class);return true;}catch (Exception e){e.getStackTrace();return false;}}public JSONObject getProperties(){return new JSONObject(true);}
对于mappings和settings的具体配置可以网上搜索,mappings的下一级要定义type,便于后续插入文档时指定type
判断索引是否存在
public boolean isExist(String indexName){String ESurl = "http://localhost:9200/" + indexName;HttpClient httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet(ESurl);HttpResponse response = null;try{response = httpClient.execute(httpGet);}catch (IOException e){e.printStackTrace();}return response.getStatusLine().getStatusCode() == 200;}
删除索引
public boolean deleteESIndex(String indexname){RestTemplate restTemplate = new RestTemplate();String ESUrl = "http://localhost:9200/" + indexname;try{restTemplate.delete(ESUrl);return true;}catch (RestClientException e){e.printStackTrace();return false;}}
添加文档
public boolean insertEsDocument(String indexname, JSONObject body, String insertId){RestTemplate restTemplate = new RestTemplate();String ESurl = "http://localhost:9200/" + indexname + "/" + "type" + "/" + insertId;ResponseEntity<String> exchange = null;try{HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.setContentType(MediaType.APPLICATION_JSON);HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(body, httpHeaders);exchange = restTemplate.exchange(ESurl, HttpMethod.POST, mapHttpEntity, String.class);return true;}catch (Exception e){e.getStackTrace();return false;}}
根据id删除一条文档
public boolean deleteEsDocumentById(String indexName, String id){RestTemplate restTemplate = new RestTemplate();String ESUrl = "http://localhost:9200/" + indexName + "/" + "type" + "/" + id;try{restTemplate.delete(ESUrl);return true;}catch (Exception e){e.printStackTrace();return false;}}
最大的叫索引,索引下面有个类型叫type创建索引的时候mapping下一级需要指定,类型下面一条数据称为一个文档。具体mappings和settings网上搜。
一般用到的话都会给。最好mappings里面指定的字段和添加文档时的字段都要一一对应。导包。
import com.alibaba.fastjson.JSONObject;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.HttpClients;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.*;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.web.client.RestClientException;import org.springframework.web.client.RestTemplate;import java.io.IOException;import java.util.Map;
