Elasticsearch Java Api
elasticsearch有很多Java Api提供使用
TransportClient
使用最原始的TransportClient来进行操作
1 2 3 4 5
| <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.4.0</version> </dependency>
|
创建TransportClient,后续操作都需要用到该对象
1 2 3
| TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getLocalHost(), 9300));
|
索引操作
创建索引管理客户端,后续索引管理都需要用到该对象
1
| IndicesAdminClient indices = client.admin().indices();
|
1 2 3
| IndicesExistsResponse existsResponse = indices.prepareExists("index2").get(); System.out.println(existsResponse.isExists());
|
1 2 3 4
| TypesExistsResponse typesExistsResponse = indices.prepareTypesExists("index2") .setTypes("default").get(); System.out.println(typesExistsResponse.isExists());
|
1 2 3 4 5 6
| CreateIndexResponse createIndexResponse = indices.prepareCreate("index3") .setSettings(Settings.builder().put("index.number_of_shards",3) .put("index.number_of_replicas",1)) .get(); System.out.println(createIndexResponse.isAcknowledged());
|
1 2 3 4 5
| UpdateSettingsResponse settingsResponse = indices.prepareUpdateSettings("index3") .setSettings(Settings.builder().put("index.number_of_replicas", 2)) .get(); System.out.println(settingsResponse.isAcknowledged());
|
1 2 3 4 5 6 7 8 9
| GetSettingsResponse getSettingsResponse = indices.prepareGetSettings("index3").get(); getSettingsResponse.getIndexToSettings().forEach( cursor -> { String index = cursor.key; Settings settings = cursor.value; Integer number_of_replicas = settings.getAsInt("index.number_of_replicas", null); } );
|
1 2 3 4 5 6
|
CreateIndexResponse createIndexAddMappingResponse = indices.prepareCreate("index4") .addMapping("default", XContentFactory.jsonBuilder().startObject().startObject("properties") .startObject("name").field("type", "keyword").endObject().endObject().endObject() ).get();
|
1 2 3 4 5 6
| GetMappingsResponse mappingsResponse = indices.prepareGetMappings("index4").get(); ImmutableOpenMap<String, MappingMetaData> index4Mappings = mappingsResponse.getMappings().get("index4");
MappingMetaData metaData = index4Mappings.get("default"); System.out.println(metaData.sourceAsMap());
|
1 2 3
| DeleteIndexResponse deleteIndexResponse = indices.prepareDelete("index4").get(); System.out.println(deleteIndexResponse.isAcknowledged());
|
文档操作
1 2 3 4 5 6 7
| Map<String,Object> doc = new HashMap<>(); doc.put("name","zhangsan"); doc.put("age",20); IndexResponse indexResponse = client.prepareIndex("index5", "default", "1") .setSource(doc).get(); System.out.println(indexResponse.status());
|
1 2 3
| GetResponse response = client.prepareGet("index5", "default", "1").get(); System.out.println(response.getSourceAsString());
|
1 2 3 4
| UpdateResponse updateResponse = client.prepareUpdate("index5", "default", "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("age", 18) .endObject()).get();
|
1 2 3
| DeleteResponse deleteResponse = client.prepareDelete("index5", "default", "1").get(); System.out.println(deleteResponse.status());
|
1 2 3 4 5 6 7
| BulkByScrollResponse deleteByQuery = DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .filter(QueryBuilders.matchQuery("age", 20)) .source("index5") .get();
System.out.println(deleteByQuery.getDeleted());
|
查询操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
MatchPhrasePrefixQueryBuilder matchPhrasePrefixQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("name", "zhangs");
MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("name", "zhangsan");
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan");
WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("name", "zhang*");
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "zhang");
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.matchQuery("name", "zhangsan")) .should(QueryBuilders.matchQuery("age", 20));
client.prepareSearch("index6") .setQuery(matchAllQueryBuilder) .setSize(10) .get();
|
RestHighLevelClient
高级客户端
1 2 3 4 5
| <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency>
|
创建客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| RestClientBuilder builder = RestClient.builder(new HttpHost(IP, PORT, "http")); CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "password")); builder.setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(1000); requestConfigBuilder.setSocketTimeout(1000); requestConfigBuilder.setConnectionRequestTimeout(1000); return requestConfigBuilder; }); builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setMaxConnTotal(30); httpClientBuilder.setMaxConnPerRoute(30); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); return httpClientBuilder; }); RestHighLevelClient restClient = new RestHighLevelClient(builder);
|
索引操作
创建索引
1 2 3 4 5 6 7 8 9 10
| final CreateIndexRequest request = new CreateIndexRequest(indexName);
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
if (response.isAcknowledged()) { System.out.println("成功");
}
|
删除索引
1 2 3
| DeleteIndexRequest request = new DeleteIndexRequest(indexName); AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
|
查看索引
1 2 3 4 5 6 7 8 9 10 11 12
| GetIndexRequest getIndexRequest = new GetIndexRequest(indexName); boolean exists = esClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName); GetIndexResponse indexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
Map<String, Settings> settings = indexResponse.getSettings(); System.out.println(settings); Map<String, MappingMetadata> mappings = indexResponse.getMappings(); System.out.println(mappings);
|
文档操作
插入数据
1 2 3 4 5 6 7
| IndexRequest indexRequest = new IndexRequest(indexName, "_doc"); Map<String, String> map = new HashMap<>(); map.put("article", "文档内容"); indexRequest = indexRequest.source(map); indexRequest = indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);
IndexResponse index = esClient.index(indexRequest, RequestOptions.DEFAULT);
|
批量插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| BulkRequest bulkRequest = new BulkRequest(indexName, "_doc");
IndexRequest indexRequest = new IndexRequest(); Map<String, String> map = new HashMap<>(); map.put("article", "文档内容1"); indexRequest = indexRequest.source(map); bulkRequest.add(indexRequest);
IndexRequest indexRequest1 = new IndexRequest(); Map<String, String> map1 = new HashMap<>(); map1.put("article", "文档内容2"); indexRequest1 = indexRequest1.source(map); bulkRequest.add(indexRequest1);
bulkRequest = bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);
BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulk.hasFailures()) { System.out.println("有错误--------"); for (BulkItemResponse response : bulk) { if (response.isFailed()) { System.out.println(response.getFailureMessage()); } } System.out.println("--------"); }
|
删除文档
1 2 3 4 5 6
| DeleteRequest request = new DeleteRequest(); request.index(indexName).id("123456"); DeleteResponse deleteResponse = esClient.delete(request, RequestOptions.DEFAULT);
System.out.println("文档删除结果: " + deleteResponse);
|
批量删除文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| BulkRequest bulkRequest = new BulkRequest();
DeleteRequest request = new DeleteRequest(); request.index(indexName).id("10001"); bulkRequest.add(request);
DeleteRequest request1 = new DeleteRequest(); request1.index(indexName).id("10002"); bulkRequest.add(request1);
BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println("文档删除结果: " + bulkResponse);
|
更新文档数据
1 2 3 4 5 6 7 8 9 10 11 12
| UpdateRequest request = new UpdateRequest(); request.index(indexName).id("123456");
App updateApp = new App(); updateApp.setName("新名称"); updateApp.setLogo_url("http://xxx.com/logo.png");
request.doc(GsonUtils.instance().toJson(updateApp), XContentType.JSON); UpdateResponse updateResponse = esClient.update(request, RequestOptions.DEFAULT);
System.out.println("文档更新结果: " + updateResponse.getResult());
|
获取文档
1 2 3 4 5 6 7
| GetRequest request = new GetRequest(); request.index(indexName).id("123456");
GetResponse getResponse = esClient.get(request, RequestOptions.DEFAULT);
System.out.println("文档 结果: " + getResponse.getSourceAsString());
|
请求体查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| SearchRequest searchRequest = new SearchRequest(IndexName); try { SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT); SearchHit[] hits = response.getHits().getHits(); for (SearchHit hit : hits) { String sourceAsString = hit.getSourceAsString(); } } catch (Exception e) { e.printStackTrace(); }
|
条件查询
查询所有数据
1 2 3 4 5 6 7 8 9 10 11 12
| SearchRequest request = new SearchRequest(); request.indices(indexName) .source( new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()) );
SearchResponse searchResponse = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits(); for(SearchHit searchHit : hits.getHits()){ System.out.println("搜索 结果: " + searchHit.getSourceAsString()); }
|
使用各种条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| SearchRequest searchRequest = new SearchRequest("indexName");
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termQuery("age", 20));
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("age", 20));
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "1"));
builder.query(boolQueryBuilder);
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age"); rangeQuery.gte("20"); rangeQuery.lte("40"); builder.query(rangeQuery);
builder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE));
builder.aggregation(AggregationBuilders.max("maxAge").field("age"));
builder.sort("age", SortOrder.DESC);
builder.from(0) .size(5);
String[] excludes = {}; String[] includes = {"name", "age"}; builder.fetchSource(includes, excludes);
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<red>").postTags("</red>"); highlightBuilder.field("name"); builder.highlighter(highlightBuilder);
searchRequest.source(builder);
LOGGER.info("索引:{},类型:{},请求信息{}", Strings.arrayToCommaDelimitedString(searchRequest.indices()), Strings.arrayToCommaDelimitedString(searchRequest.types()), searchRequest.source().toString());
SearchResponse search = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
|