官方文档
https://www.elastic.co/guide/en/elastic-stack-overview/current/api-java.html
高级客户端RestHighLevelClient
下载ElasticSearch7.1.1 Windows安装包
启动脚本elasticsearch.bat
测试
JavaAPI 操作Elasticsearch
批量创建,条件搜索,高亮突出
package compretty.testing.elasticsearch;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pretty.common.entity.User;
public class ElasticSearchTesting {
public static void main(String[] args) throws IOException {
/Client
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost("127.0.0.1", 9200)
)
.setRequestConfigCallback(
new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder
.setConnectTimeout(5000) //连接超时(默认为1秒)
.setSocketTimeout(60000);//套接字超时(默认为30秒)
}
}
)
.setMaxRetryTimeoutMillis(60000)//调整最大重试超时时间(默认为30秒)
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom().setIoThreadCount(1).build());//线程数
}
}
);
RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
String index = null;
String id = null;
Long version = null;
//创建index
User user = new User(1, "pretty", "pretty");
user = new User(1, "root", "123456");
List<User> list = new ArrayList<User>();
list.add(user);
list.add(new User(2, "root", "123456"));
list.add(new User(3, "admin", "abc"));
list.add(new User(4, "pretty-testing", "123456"));
list.add(new User(5, "pretty-common", "123456"));
list.add(new User(6, "pretty-gateway", "123456"));
String jsonData = new ObjectMapper().writeValueAsString(user);
System.out.println("User:"+jsonData);
IndexRequest indexRequest = new IndexRequest("posts").id("1").source(jsonData, XContentType.JSON);
//批量
BulkRequest request = new BulkRequest();
for(User u : list) {
jsonData = new ObjectMapper().writeValueAsString(u);
request.add(new IndexRequest("posts").id(u.getId().toString()).source(jsonData, XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
//批量响应
for(BulkItemResponse bulkItemResponse:bulkResponse){
DocWriteResponse itemResponse = bulkItemResponse.getResponse();
if(bulkItemResponse.getOpType()== DocWriteRequest.OpType.INDEX
|| bulkItemResponse.getOpType()== DocWriteRequest.OpType.CREATE){
IndexResponse indexResponse =(IndexResponse)itemResponse;
System.out.println("处理索引操作的响应"+indexResponse);
} else if(bulkItemResponse.getOpType()== DocWriteRequest.OpType.UPDATE){
UpdateResponse updateResponse =(UpdateResponse)itemResponse;
System.out.println("处理更新操作的响应"+updateResponse);
} else if(bulkItemResponse.getOpType()== DocWriteRequest.OpType.DELETE){
DeleteResponse deleteResponse =(DeleteResponse)itemResponse;
System.out.println("处理删除操作的响应"+deleteResponse);
}
}
//同步执行
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
index = indexResponse.getIndex();
id = indexResponse.getId();
version = indexResponse.getVersion();
System.out.println(index);
System.out.println(id);
System.out.println(version);
Result result = indexResponse.getResult();
if(result==Result.CREATED) {
System.out.println("创建");
} else if(result==Result.UPDATED) {
System.out.println("覆盖");
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if(shardInfo.getTotal() != shardInfo.getSuccessful()){
}
if(shardInfo.getFailed()> 0){
for(ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
System.out.println(reason);
System.out.println(index);
System.out.println(id);
}
}
///获取index
/*GetRequest getRequest = new GetRequest("posts", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
index = getResponse.getIndex();
id = getResponse.getId();
System.out.println(id);
System.out.println(id);
if(getResponse.isExists()){
version = getResponse.getVersion();
String sourceAsString = getResponse.getSourceAsString();
//Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
//byte [] sourceAsBytes = getResponse.getSourceAsBytes();
System.out.println(version);
System.out.println(sourceAsString);
} else {
System.out.println("没有找到");
}*/
//搜索
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.query(QueryBuilders.termQuery("username", "pretty"));
searchSourceBuilder.from(0);//设置from确定结果索引的选项以开始搜索。默认为0
searchSourceBuilder.size(10);//设置size确定要返回的搜索匹配数的选项。默认为10
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//设置一个可选的超时,控制允许搜索的时间
/*MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("username", "pretty");
matchQueryBuilder.fuzziness(Fuzziness.AUTO);//在匹配查询上启用模糊匹配
matchQueryBuilder.prefixLength(3);//在匹配查询上设置前缀长度选项
matchQueryBuilder.maxExpansions(10);//设置最大扩展选项以控制查询的模糊过程
searchSourceBuilder.query(matchQueryBuilder);
searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));
String [] includeFields = new String [] {"title","innerObject.*"};
String [] excludeFields = new String [] {"username"};
searchSourceBuilder.fetchSource(includeFields, excludeFields);*/
//高量突出
HighlightBuilder highlightBuilder = new HighlightBuilder();
HighlightBuilder.Field highlightTitle=new HighlightBuilder.Field("username");
highlightTitle.highlighterType("unified");//荧光笔类型
highlightBuilder.field(highlightTitle);
highlightBuilder.preTags("<span style=\"color:red\">");//前
highlightBuilder.postTags("</span>");//后
searchSourceBuilder.highlighter(highlightBuilder);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("posts");
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
TotalHits totalHits = hits.getTotalHits();
long numHits = totalHits.value;
TotalHits.Relation relation = totalHits.relation;
float maxScore = hits.getMaxScore();
System.out.println(numHits);
System.out.println(relation);
System.out.println(maxScore);
//嵌套在SearchHits可以迭代的单个搜索结果中
SearchHit [] searchHits = hits.getHits();
Float score = null;
for(SearchHit hit:searchHits){
//使用SearchHit做一些事情
index = hit.getIndex();
id = hit.getId();
score = hit.getScore();
System.out.println(index);
System.out.println(id);
System.out.println(score);
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
System.out.println(sourceAsMap);
System.out.println(highlightFields);
}
关闭连接
client.close();
}
}
运行结果
创建或覆盖
批量
高亮