学完elasticsearch的API操作,为了防止遗忘,写篇博客记录下来,方便以后使用。
1.创建一个SpringBoot项目,添加elasticsearch的依赖
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-data-elasticsearch
</artifactId>
</dependency>
通过在pom.xml文件中加入下面配置,设置elasticsearch的版本
<properties>
<elasticsearch.version>7.6.1
</elasticsearch.version>
</properties>
2.创建配置文件,来配置elasticsearch的ip和端口号以及使用的协议
配置代码如下:
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient
restHighLevelClient(){
RestHighLevelClient client
;
client
= new RestHighLevelClient(
RestClient
.builder(new HttpHost("127.0.0.1",9200,"http"))
);
return client
;
}
}
在bean包下创建一个实体类,用来测试上传数据
package com
.hist
.testesapi
.bean
;
import lombok
.AllArgsConstructor
;
import lombok
.Data
;
import lombok
.NoArgsConstructor
;
import org
.springframework
.boot
.context
.properties
.ConfigurationProperties
;
import org
.springframework
.stereotype
.Component
;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(value
= "user")
public class User {
private String name
;
private Integer id
;
private String sex
;
}
为了能够方便将对象转为json字符串,引入fastjson依赖
<dependency>
<groupId>com.alibaba
</groupId>
<artifactId>fastjson
</artifactId>
<version>1.2.62
</version>
</dependency>
3.配置完成后,开始Elasticsearch的常用API的测试
API的测试在测试类中完成
注入客户端对象
@SpringBootTest
class TestEsApiApplicationTests {
@Autowired
RestHighLevelClient restHighLevelClient
;
}
3.1测试获取索引,判断其是否存在
@Test
void testExistsIndex() throws IOException
{
GetIndexRequest getIndexRequest
= new GetIndexRequest("index");
boolean exists
= restHighLevelClient
.indices().exists(getIndexRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(exists
);
}
3.2测试创建索引
@Test
void testCreateIndex() throws IOException
{
CreateIndexRequest createIndexRequest
= new CreateIndexRequest("index");
AcknowledgedResponse response
= restHighLevelClient
.indices().create(createIndexRequest
,RequestOptions
.DEFAULT
);
System
.out
.println(response
);
}
3.3测试删除索引
@Test
void testDeleteIndex(){
DeleteIndexRequest request
= new DeleteIndexRequest("index");
AcknowledgedResponse delete
= restHighLevelClient
.indices().delete(request
, RequestOptions
.DEFAULT
);
System
.out
.println(delete
.isAcknowledged());
}
3.4测试删除文档
@Test
void testAddDoucment2() throws IOException
{
User user
= new User("李四", 1, "男");
IndexRequest request
= new IndexRequest("index");
request
.id("1");
request
.timeout("1s");
request
.source(JSON
.toJSONString(user
),XContentType
.JSON
);
IndexResponse indexResponse
= restHighLevelClient
.index(request
, RequestOptions
.DEFAULT
);
System
.out
.println(indexResponse
.toString());
System
.out
.println(indexResponse
.status());
}
3.5获取文档,判断是否存在
@Test
void testIsExistsDoucment() throws IOException
{
GetRequest getRequest
= new GetRequest("index", "1");
getRequest
.fetchSourceContext(new FetchSourceContext(false));
getRequest
.storedFields("_none_");
boolean exists
= restHighLevelClient
.exists(getRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(exists
);
}
3.6获取文档的内容
@Test
void testGetDocument() throws IOException
{
GetRequest getRequest
= new GetRequest("index", "1");
GetResponse getResponse
= restHighLevelClient
.get(getRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(getResponse
.getSourceAsString());
System
.out
.println(getResponse
);
}
3.7更新文档的信息
@Test
void testUpdateRequest(){
UpdateRequest updateRequest
= new UpdateRequest("index", "1");
updateRequest
.timeout(new TimeValue(1,TimeUnit
.MILLISECONDS
));
User user
= new User("aaa", 1, "女");
updateRequest
.doc(JSON
.toJSONString(user
),XContentType
.JSON
);
UpdateResponse updateResponse
= restHighLevelClient
.update(, RequestOptions
.DEFAULT
);
System
.out
.println(updateResponse
.status());
}
3.8删除文档记录
@Test
void testDeleteRequest() throws IOException
{
DeleteRequest deleteRequest
= new DeleteRequest("index", "1");
deleteRequest
.timeout(new TimeValue(10,TimeUnit
.MILLISECONDS
));
DeleteResponse deleteResponse
= restHighLevelClient
.delete(deleteRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(deleteResponse
.status());
}
3.8批量插入数量——指定id
@Test
void testBulkRequest() throws IOException
{
BulkRequest bulkRequest
= new BulkRequest();
bulkRequest
.timeout("10s");
ArrayList
<User> userArrayList
= new ArrayList<>();
userArrayList
.add(new User("tom1",1,"man"));
userArrayList
.add(new User("tom2",2,"man"));
userArrayList
.add(new User("tom3",3,"man"));
userArrayList
.add(new User("tom4",4,"man"));
userArrayList
.add(new User("tom5",5,"man"));
userArrayList
.add(new User("tom6",6,"man"));
for (int i
= 0; i
> userArrayList
.size(); i
++){
bulkRequest
.add(
new IndexRequest("index").id(""+(i
+1)).source(
JSON
.toJSONString(userArrayList
.get(i
)),XContentType
.JSON
));
}
BulkResponse bulkResponse
= restHighLevelClient
.bulk(bulkRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(bulkResponse
.status());
}
3.9批量插入,不指定id
@Test
void testBulkRequest() throws IOException
{
BulkRequest bulkRequest
= new BulkRequest();
bulkRequest
.timeout("10s");
ArrayList
<User> userList
= new ArrayList<>();
userList
.add(new User("hist1",1,"man"));
userList
.add(new User("hist2",2,"man"));
userList
.add(new User("hist3",3,"man"));
userList
.add(new User("hist4",4,"man"));
userList
.add(new User("hist5",5,"man"));
userList
.add(new User("hist6",6,"man"));
for (int i
= 0; i
< userList
.size(); i
++) {
bulkRequest
.add(
new IndexRequest("hudashuai").source(JSON
.toJSONString(userList
.get(i
)),XContentType
.JSON
)
);
}
BulkResponse bulk
= restHighLevelClient
.bulk(bulkRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(bulk
.status());
}
3.10查询
@Test
void testSearch() throws IOException
{
SearchRequest searchRequest
= new SearchRequest("index");
SearchSourceBuilder searchSourceBuilder
= new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder
= QueryBuilders
.termQuery("name", "tom1");
searchSourceBuilder
.query(termQueryBuilder
);
searchSourceBuilder
.timeout(new TimeValue(30,TimeUnit
.MILLISECONDS
));
searchRequest
.source(searchSourceBuilder
);
SearchResponse searchResponse
= restHighLevelClient
.search(searchRequest
, RequestOptions
.DEFAULT
);
System
.out
.println(JSON
.toJSONString(searchResponse
.getHits()));
System
.out
.println("====================");
for (SearchHit hit
: searchResponse
.getHits().getHits()) {
System
.out
.println(hit
.getSourceAsMap());
}
}
3.11高亮查询
@Test
void testHightLighter() throws IOException
{
SearchRequest searchRequest
= new SearchRequest("index");
SearchSourceBuilder searchSourceBuilder
= new SearchSourceBuilder();
searchSourceBuilder
.from(1);
searchSourceBuilder
.size(10);
TermQueryBuilder termQueryBuilder
= QueryBuilders
.termQuery("name", "tom");
searchSourceBuilder
.query(termQueryBuilder
);
searchSourceBuilder
.timeout(new TimeValue(60,TimeUnit
.MILLISECONDS
));
HighlightBuilder highlightBuilder
= new HighlightBuilder();
highlightBuilder
.field("name");
highlightBuilder
.requireFieldMatch(false);
highlightBuilder
.preTags("<span style='color:red;'");
highlightBuilder
.postTags("</span>");
searchSourceBuilder
.highlighter(highlightBuilder
);
searchRequest
.source(searchSourceBuilder
);
SearchResponse searchResponse
= restHighLevelClient
.search(searchRequest
, RequestOptions
.DEFAULT
);
ArrayList
<Map
<String,Object>> list
= new ArrayList<>();
for (SearchHit hit
: searchResponse
.getHits()) {
Map
<String, HighlightField> highlightFields
= hit
.getHighlightFields();
HighlightField name
= highlightFields
.get("name");
Map
<String, Object> sourceAsMap
= hit
.getSourceAsMap();
if(name
!= null
){
Text
[] fragments
= name
.fragments();
String newName
= "";
for (Text fragment
: fragments
) {
newName
+= fragment
;
}
sourceAsMap
.put("name",newName
);
}
list
.add(sourceAsMap
);
}
for (Map
<String, Object> stringObjectMap
: list
) {
System
.out
.println(stringObjectMap
);
}
}