elasticsearch - Java 작업 (RestHighLevelClient)
11858 단어 elasticsearchJava
의지 하 다
org.elasticsearch.client
elasticsearch-rest-client
7.2.0
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.2.0
org.elasticsearch
elasticsearch
org.elasticsearch.client
elasticsearch-rest-client
org.elasticsearch
elasticsearch
7.2.0
es 작업 클래스
/**
* es
*/
public class EsHandler {
private static final int FROM = 0;
private static final int SIZE = 50;
private static final String HOST = "192.168.1.66";
private static final int PORT = 9200;
private static final String SCHEME = "http";
private static final int CONNECTION_TIMEOUT = 4000;
private static final int SOCKET_TIMEOUT = 30000;
private static final int CONNECTION_REQUEST_TIMEOUT = 2000;
private static final int MAX_CONN_TOTAL = 100;
private static final int MAX_CONN_PER_ROUTE = 100;
private static final int IO_THREAD_COUNT = 10;
private static final RestHighLevelClient REST_HIGH_LEVEL_CLIENT;
static {
RestClientBuilder builder = RestClient.builder(new HttpHost(HOST, PORT, SCHEME));
// httpclient
builder.setRequestConfigCallback(configBuilder -> {
configBuilder.setConnectTimeout(CONNECTION_TIMEOUT);
configBuilder.setSocketTimeout(SOCKET_TIMEOUT);
configBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT);
return configBuilder;
});
CredentialsProvider provider = new BasicCredentialsProvider();
// ,
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "Msx985211_TD"));
// httpclient ,
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setDefaultCredentialsProvider(provider);
httpClientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
httpClientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);
httpClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(IO_THREAD_COUNT).build());
return httpClientBuilder;
});
REST_HIGH_LEVEL_CLIENT = new RestHighLevelClient(builder);
}
/**
*
*/
public static RestHighLevelClient getRestHighLevelClient() {
return REST_HIGH_LEVEL_CLIENT;
}
/**
*
*/
public void createIndex(String indexName) throws IOException {
if (isIndexExist(indexName)) {
return;
}
REST_HIGH_LEVEL_CLIENT.indices().create(new CreateIndexRequest(indexName).settings(Settings.EMPTY), RequestOptions.DEFAULT);
}
/**
*
*/
public void deleteIndex(String indexName) throws IOException {
if (!isIndexExist(indexName)) {
return;
}
REST_HIGH_LEVEL_CLIENT.indices().delete(new DeleteIndexRequest(indexName), RequestOptions.DEFAULT);
}
/**
*
*/
private boolean isIndexExist(String indexName) throws IOException {
return REST_HIGH_LEVEL_CLIENT.indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
}
/**
*
*/
public void save(String index, T t) throws IOException {
if (isDataExist(index, t)) {
return;
}
REST_HIGH_LEVEL_CLIENT.index(new IndexRequest(index).id(t.getId()).source(JSON.toJSONString(t), XContentType.JSON), RequestOptions.DEFAULT);
}
//
public void batchSave(String index, List ts) throws IOException {
if (null == ts || ts.isEmpty()) {
return;
}
// , DeleteRequest、IndexRequest UpdateRequest
BulkRequest request = new BulkRequest();
ts.forEach(t -> request.add(new IndexRequest(index).id(t.getId()).source(JSON.toJSONString(t), XContentType.JSON)));
REST_HIGH_LEVEL_CLIENT.bulk(request, RequestOptions.DEFAULT);
}
/**
*
*/
public void update(String index, T t) throws IOException {
if (!isDataExist(index, t)) {
return;
}
UpdateRequest request = new UpdateRequest().index(index).id(t.getId()).doc(JSON.toJSONString(t), XContentType.JSON);
REST_HIGH_LEVEL_CLIENT.update(request, RequestOptions.DEFAULT);
}
/**
*
*/
public void delete(String index, String id) throws IOException {
DeleteRequest request = new DeleteRequest(index).id(id);
REST_HIGH_LEVEL_CLIENT.delete(request, RequestOptions.DEFAULT);
}
/**
*
*/
private boolean isDataExist(String index, T t) throws IOException {
GetRequest request = new GetRequest(index).id(t.getId());
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");
return REST_HIGH_LEVEL_CLIENT.exists(request, RequestOptions.DEFAULT);
}
/**
* id
*/
public T query(String index, T t) throws IOException {
GetRequest request = new GetRequest(index).id(t.getId());
return JSON.parseObject(REST_HIGH_LEVEL_CLIENT.get(request, RequestOptions.DEFAULT).getSourceAsString(), (Class) t.getClass());
}
/**
*
*/
public Page queryPage(String index, T t) throws IOException {
Page page = t.getPage();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(getBoolQueryBuilder(t));
searchSourceBuilder.from(t.getPage().getPageNo()).size(t.getPage().getPageSize());
SearchRequest request = new SearchRequest(index).source(searchSourceBuilder);
SearchHits searchHits = REST_HIGH_LEVEL_CLIENT.search(request, RequestOptions.DEFAULT).getHits();
page.setTotal(searchHits.getTotalHits().value);
Iterator searchHitIterator = searchHits.iterator();
List list = new ArrayList<>();
page.setList(list);
while (searchHitIterator.hasNext()) {
String json = searchHitIterator.next().getSourceAsString();
System.out.println(json);
list.add(JSON.parseObject(json, (Class) t.getClass()));
}
return page;
}
/**
*
*/
public List queryCondition(String index, T t) throws IOException {
if (null == t.getPage()) {
Page page = new Page<>();
page.setPageNo(FROM);
page.setPageSize(SIZE);
t.setPage(page);
}
Page page = queryPage(index, t);
return page.getList();
}
public void closeClient() {
try {
REST_HIGH_LEVEL_CLIENT.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private BoolQueryBuilder getBoolQueryBuilder(T t) {
BoolQueryBuilder builder = new BoolQueryBuilder();
if (null != t.getExtension() && !t.getExtension().isEmpty()) {
//
if (null != t.getExtension().get(BaseEntity.MATCH)) {
t.getExtension().get(BaseEntity.MATCH).forEach((k, v) -> builder.must(QueryBuilders.matchQuery(k, v)));
}
//
if (null != t.getExtension().get(BaseEntity.TERM)) {
t.getExtension().get(BaseEntity.TERM).forEach((k, v) -> builder.must(QueryBuilders.termQuery(k, v)));
}
//
if (null != t.getExtension().get(BaseEntity.PREFIX)) {
t.getExtension().get(BaseEntity.PREFIX).forEach((k, v) -> builder.must(QueryBuilders.matchPhrasePrefixQuery(k, v).maxExpansions(500000)));
}
//
if (null != t.getExtension().get(BaseEntity.WILD)) {
t.getExtension().get(BaseEntity.WILD).forEach((k, v) -> builder.must(QueryBuilders.wildcardQuery(k, v)));
}
}
//
if (null != t.getMulExtension() && !t.getMulExtension().isEmpty()) {
t.getMulExtension().forEach((k, v) -> builder.must(QueryBuilders.multiMatchQuery(k, v.toArray(new String[v.size()]))));
}
//
if (null != t.getRangeExtension() && !t.getRangeExtension().isEmpty()) {
t.getRangeExtension().forEach((k, v) -> builder.must(QueryBuilders.rangeQuery(k).gte(v.get(0)).lte(v.get(1))));
}
return builder;
}
}
실체 류
/**
*
*/
@Data
public abstract class BaseEntity implements Serializable {
private String id;
/**
*
*/
private Map> extension;
/**
*
*/
private Map> mulExtension;
/**
*
*/
private Map> rangeExtension;
private Page page;
public static final String MATCH = "match";
public static final String TERM = "term";
public static final String WILD = "wild";
public static final String PREFIX = "prefix";
}
/**
*
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class Building extends BaseEntity {
/**
* ,
*/
private String name;
/**
* : , , ...... ,
*/
private String type;
/**
* ,
*/
private String location;
/**
* ,
*/
private double height;
private double[] center;
enum BuildingType {
STRUCTURE_FRAME(" "),
STRUCTURE_SHEAR_WALL(" "),
STRUCTURE_STEEL(" ");
private String name;
BuildingType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
테스트 클래스
public class Test {
private static final String INDEX_NAME = "project_building";
public static void main(String[] args) {
EsHandler esHandler = new EsHandler<>();
try {
//
esHandler.batchSave(INDEX_NAME, getBuildings());
String id = "2bde0d1c-c44b-4482-9b53-190dcf1b9db3";
Building building = new Building();
building.setId(id);
//
building = esHandler.query(INDEX_NAME, building);
building.setName(" ");
//
esHandler.update(INDEX_NAME, building);
//
esHandler.delete(INDEX_NAME, id);
//
building = new Building();
Map> extension = new HashMap<>();
Map match = new HashMap<>();
match.put("name", " ");
extension.put(BaseEntity.MATCH, match);
building.setExtension(extension);
esHandler.queryCondition(INDEX_NAME, building);
} catch (IOException e) {
e.printStackTrace();
} finally {
esHandler.closeClient();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
kafka connect e elasticsearch를 관찰할 수 있습니다.No menu lateral do dashboard tem a opção de connectors onde ele mostra todos os clusters do kafka connect conectados atu...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.