Elasticsearch搜索引擎的简单连接:
maven导入以下配置:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
<!-- 以下配置 springboot 项目可忽略 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
示例:
1. 配置连接客户端 RestHighLevelClient
@Slf4j
@Configuration
public class MyConfig {
//超时时间设为5分钟
private static final int TIME_OUT = 5 * 60 * 1000;
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
private final int connectTimeOut = 1000; // 连接超时时间
private final int socketTimeOut = 30000; // 连接超时时间
private final int connectionRequestTimeOut = 500; // 获取连接的超时时间
private final int maxConnectNum = 100; // 最大连接数
private final int maxConnectPerRoute = 100; // 最大路由连接数
//权限验证
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// @Value("${elasticsearch.address}")
private final String[] address = {"localhost:9200"};
@Bean(name = "restHighLevelClient")
public RestHighLevelClient restHighLevelClient() {
HttpHost[] hosts = Arrays.stream(address)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
log.debug("hosts:{}", Arrays.toString(hosts));
System.out.println("hosts:{}" + Arrays.toString(hosts));
//配置权限验证
// credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
return new RestHighLevelClient(RestClient.builder(hosts)
.setRequestConfigCallback(
requestConfigBuilder ->
requestConfigBuilder
.setConnectTimeout(connectTimeOut)
.setSocketTimeout(socketTimeOut)
.setConnectionRequestTimeout(connectionRequestTimeOut))
.setHttpClientConfigCallback(
httpClientBuilder ->
httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)
.setMaxConnTotal(maxConnectNum)
.setMaxConnPerRoute(maxConnectPerRoute))
.setRequestConfigCallback(
requestConfigBuilder ->
requestConfigBuilder.setSocketTimeout(TIME_OUT)));
}
/**
* 处理请求地址
* @param s address
* @return HttpHost
*/
private HttpHost makeHttpHost(String s) {
assert !Objects.isNull(s);
String[] address = s.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
return null;
}
}
}
2. CURD示例:
@Slf4j
@RestController
public class SearchController {
/**
* 8.0版本开始将完全移除TransportClient,使用RestHighLevelClient取代
*/
@Resource
RestHighLevelClient restHighLevelClient;
@GetMapping("/index")
public SearchResponse index() throws IOException {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
SearchRequest rq = new SearchRequest()
//索引
.indices("account")
//各种组合条件
.source(sourceBuilder);
//请求
System.out.println(rq.source().toString());
return restHighLevelClient.search(rq, RequestOptions.DEFAULT);
}
@GetMapping("/query")
public String query() throws IOException {
MatchQueryBuilder matchQueryBuilder = QueryBuilders
.matchQuery("name", "afred");
MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders
.multiMatchQuery("入门", "name", "lastname");
//查询条件
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(matchQueryBuilder)
.must(multiMatchQueryBuilder);
//分页
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(boolQueryBuilder)
.from(0)
.size(100)
.timeout(new TimeValue(60, TimeUnit.SECONDS));
//查询
SearchRequest searchRequest = new SearchRequest()
.allowPartialSearchResults(true)
//在es7中使用_doc作为默认的type,并且es8中将会被移除
//.types("doc")
.indices("account")
.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("结果总数:"+ response.getHits().getTotalHits().value);
SearchHits hits = response.getHits(); //SearchHits提供有关所有匹配的全局信息,例如总命中数或最高分数:
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
log.info("search -> {}",hit.getSourceAsString());
}
return Arrays.toString(searchHits);
}
@GetMapping("/add")
public String add() throws IOException {
Map<String, Object> source = new LinkedHashMap<>();
source.put("name", "嘤嘤嘤?");
source.put("lastname", "嘤嘤嘤!");
source.put("job_description", "嘤嘤嘤");
JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
jsonObject.put("type", "person");
jsonObject.put("source", new JSONObject(source));
IndexRequest indexRequest = new IndexRequest("account").source(jsonObject.toJSONString(), XContentType.JSON);
IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
log.info("search -> {}", response.toString());
return response.toString();
}
@GetMapping("/delete")
public String delete(@RequestParam(name = "id") String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest()
.index("account")
.id(id)
.timeout(new TimeValue(60, TimeUnit.SECONDS));
DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
log.info("search -> {}", response.toString());
return response.toString();
}
@GetMapping("/update")
public String update() throws IOException {
Map<String, Object> source = new LinkedHashMap<>();
source.put("name", "111?");
source.put("lastname", "222!");
source.put("job_description", "333");
JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
jsonObject.put("source", new JSONObject(source));
UpdateRequest updateRequest = new UpdateRequest("account", "ad5ManMB1VCSKbBy8PTJ")
.doc(jsonObject, XContentType.JSON)
.retryOnConflict(3)
.timeout(new TimeValue(60, TimeUnit.SECONDS));
UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
log.info("search -> {}", response.toString());
return response.toString();
}
}