一、原生Elasticsearch
1)导入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.2</version>
</dependency>
2)创建索引
//索引管理
public class IndexManager {
private RestHighLevelClient client;
@Before
public void init(){
//创建一个client对象
client =new RestHighLevelClient(RestClient.builder(
new HttpHost("192.168.92.134",9200)
));
}
/**
* 创建索引
* @throws Exception
*/
@Test
public void creatIndex() throws Exception{
//获取索引管理对象
IndicesClient indicesClient = client.indices();
//两个参数 2、请求选项 使用默认值 配置请求头、主要用于认证
//1、创建索引请求对象 参数创建索引名称
CreateIndexRequest request = new CreateIndexRequest("hello");
CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);
//显示结果
System.out.println(response);
}
/**
* 创建带有settings的索引
* @throws Exception
*/
@Test
public void createIndex2() throws Exception{
CreateIndexRequest request = new CreateIndexRequest("hello1").
settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1));
client.indices().create(request,RequestOptions.DEFAULT);
}
/**
* 创建带有settings和mappings的索引
* @throws Exception
*/
@Test
public void createIndex3() throws Exception{
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()//相当于json中的“{”
.startObject("properties")
.startObject("id")
.field("type","long")
.endObject()//相当于json中的“}”
.startObject("title")
.field("type","text")
.field("analyzer","ik_smart")
.field("store",true)
.endObject()
.startObject("content")
.field("type","text")
.field("analyzer","ik_smart")
.field("store",true)
.endObject()
.endObject()
.endObject();
CreateIndexRequest request = new CreateIndexRequest("hello3").
settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1).build()).mapping(builder);
client.indices().create(request,RequestOptions.DEFAULT);
}
/**
* 删除索引
* @throws Exception
*/
@Test
public void delectIndex() throws Exception{
client.indices().delete(new DeleteIndexRequest("hello"),RequestOptions.DEFAULT);
}
/**
* 修改索引中的mappings
* @throws Exception
*/
@Test
public void putMapping() throws Exception{
String mappings = "{\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"id\":{\n" +
" \"type\": \"long\"\n" +
" },\n" +
" \"title\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"standard\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n";
PutMappingRequest request = new PutMappingRequest("helle1")
.source(mappings, XContentType.JSON);
client.indices().putMapping(request,RequestOptions.DEFAULT);
}
}
3)创建文档
//创建文档
public class DecumentManager {
private RestHighLevelClient client;
@Before
public void init(){
//创建一个client对象
client =new RestHighLevelClient(RestClient.builder(
new HttpHost("192.168.92.134",9200)
));
}
/**
* 创建文档
* @throws Exception
*/
@Test
public void addDecument() throws Exception{
String document ="{\"id\":\"1\",\"title\":\"测试文档1\",\"concent\":\"测试文档内容\"}";
//创建indexRequest对象,其中包含了索引名称文档id、文档内容
IndexRequest indexRequest = new IndexRequest()
.index("hello1")
.id("1")
.source(document, XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
}
/**
* 更新文档
* @throws Exception
*/
@Test
public void updateDecument() throws Exception{
String document ="{\"id\":\"1\",\"title\":\"测试1文档1\",\"concent\":\"测试文档内容\"}";
UpdateRequest request = new UpdateRequest()
.index("hello1")
.id("1")
.doc(document, XContentType.JSON);
client.update(request,RequestOptions.DEFAULT);
}
@Test
public void deleteDocument() throws Exception{
DeleteRequest request = new DeleteRequest("hello1","1");
client.delete(request,RequestOptions.DEFAULT);
}
/**
* 查询文档
* @throws Exception
*/
@Test
public void getDocument() throws Exception{
GetRequest getRequest = new GetRequest("hello1","1");
client.get(getRequest,RequestOptions.DEFAULT);
}
/**
* 批量添加
* @throws Exception
*/
@Test
public void bathDocument() throws Exception{
String json = "[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"]";
JSONArray jsonArray = JSONObject.parseArray(json);
BulkRequest request = new BulkRequest();
jsonArray.stream().forEach(j->{
IndexRequest r = new IndexRequest()
.index("hello1")
.id(((JSONObject)j).getString("id"))
.source(((JSONObject)j).toJSONString(),XContentType.JSON);
request.add(r);
});
client.bulk(request,RequestOptions.DEFAULT);
}
}
3)查询索引
//查询索引内容
public class IndexSearch {
private RestHighLevelClient client;
@Before
public void init(){
//创建一个client对象
client =new RestHighLevelClient(RestClient.builder(
new HttpHost("192.168.92.134",9200)
));
}
/**
* 查询所有
* @throws Exception
*/
@Test
public void searchIndex() throws Exception{
SearchRequest request = new SearchRequest("hello1")
.source(new SearchSourceBuilder()
.query(QueryBuilders.matchAllQuery()));//设置查询方式
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//从response对象中取出数据
SearchHits searchHits =response.getHits();
long total = searchHits.getTotalHits().value;
System.out.println("查询的总计录数"+total);
SearchHit[] searchHits1 = searchHits.getHits();
Stream.of(searchHits1).forEach(e->{
System.out.println(e);
});
}
/**
* 根据title进行查询
* @throws Exception
*/
@Test
public void termSearch() throws Exception{
SearchRequest request = new SearchRequest("hello1")
.source(new SearchSourceBuilder()
.query(QueryBuilders.termQuery("title","品")));//设置查询方式
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
printResult(response);
}
public void printResult(SearchResponse response){
//从response对象中取出数据
SearchHits searchHits =response.getHits();
long total = searchHits.getTotalHits().value;
System.out.println("查询的总计录数"+total);
SearchHit[] searchHits1 = searchHits.getHits();
Stream.of(searchHits1).forEach(e->{
System.out.println(e.getSourceAsString());
System.out.println(e.getHighlightFields());
});
}
/**
* 设置分页信息
* @throws Exception
*/
@Test
public void searchPage() throws Exception{
SearchRequest request = new SearchRequest("hello1")
.source(new SearchSourceBuilder()
//查询条件
.query(QueryBuilders.matchAllQuery())
//过滤
.postFilter(QueryBuilders.termQuery("title","品"))
//高亮显示
.highlighter(new HighlightBuilder()
.field("title").field("content")
.preTags("<em>")
.postTags("</em>"))
//分页条件
.from(0)
.size(30)
);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
printResult(response);
}
}
二、使用SpringBoot的Elasticsearch
1)导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
设置对应自己的Elasticsearch的版本号
<elasticsearch.version>7.10.2</elasticsearch.version>
2)配置application配置文件
spring:
elasticsearch:
rest:
uris: xxx.xxx.xxx.xxx:9200//xx是自己的ip地址
3)创建实体类
@Data
@Document(indexName = "blog_1",shards = 5,replicas = 1)
public class Blog {
@Id
@Field(type = FieldType.Long,store = true)
private Long id;
@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
private String title;
@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
private String content;
@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
private String comment;
@Field(type = FieldType.Text,store = true)
private String mobile;
}
4)创建索引
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DlmallSearchApplication.class)//因为在测试类给他设置启动
public class RestTemplateTest {
@Autowired
private ElasticsearchRestTemplate template;
/**
* 创建名为mytest的索引
* @throws Exception
*/
@Test
public void createIndex() throws Exception{
template.indexOps(IndexCoordinates.of("mytest")).create();
}
/**
* 创建名为mytest的索引并设置mapping信息
* @throws Exception
*/
@Test
public void putMapping(){
Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);
template.indexOps(IndexCoordinates.of("mytest")).putMapping(mapping);
}
/**
* 根据实体类对象创建mapping
*/
@Test
public void createIndexWithMapping(){
// template.indexOps(Blog.class).create();
Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);
template.indexOps(Blog.class).putMapping(mapping);
}
/**
* 删除索引
*/
@Test
public void deleteIndex(){
template.indexOps(IndexCoordinates.of("hello1")).delete();
}
}
5)创建文档和查询文档
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BlogRepositoryTest {
@Autowired
private BlogRepository blogRepository;
/**
* 根据实体类blog创建相对应得文档信息
*/
@Test
public void addDocument(){
Blog blog = new Blog();
blog.setId(1l);
blog.setTitle("测试1");
blog.setContent("neirong1");
blog.setComment("内容");
blog.setMobile("1111111111");
blogRepository.save(blog);
}
/**
* 更新文档
*/
@Test
public void updateDocument(){
Optional<Blog> optional = blogRepository.findById(1l);
if (optional.isPresent()){
Blog blog = optional.get();
blog.setTitle("hello word");
blogRepository.save(blog);
}
}
/**
* 删除文档
*/
@Test
public void deleteDocument(){
blogRepository.deleteById(1l);
}
/**
* 根据id查询文档和查询全部进行分页
*/
@Test
public void getById(){
Optional<Blog> optional = blogRepository.findById(1l);
Blog blog = optional.get();
System.out.println(blog);
//分页
Iterable<Blog> all = blogRepository.findAll(PageRequest.of(1, 10));
all.forEach(e->{
System.out.println(e);
});
}
}
6)使用批量
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BulkTest {
@Autowired
private ElasticsearchRestTemplate template;
/**
* 批量添加索引文档内容
*/
@Test
public void bulkBlog(){
JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":4, \"title\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"content\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"]");
List<IndexQuery> list = json.stream().map(query -> {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(((JSONObject) query).getString("id"));
indexQuery.setSource(((JSONObject) query).toJSONString());
return indexQuery;
}).collect(Collectors.toList());
template.bulkIndex(list, IndexCoordinates.of("mytest"));
}
/**
* 批量添加索引文档内容(使用实体类对象)
*/
@Test
public void bulkSaveBlog(){
JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
"]");
List<Blog> list = json.stream().map(query -> {
JSONObject jsonObject = (JSONObject) query;
Blog blog = jsonObject.toJavaObject(Blog.class);
return blog;
}).collect(Collectors.toList());
template.save(list);
}
}