使用的版本
Spring boot 2.0.0.RELEASE
Elasticsearch 6.6.0
引入spring-boot-starter-data-elasticsearch依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
创建Entity
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
//indexName:索引,type:类型
@Document(indexName="db_index",type="user")
public class User{
//标记Id
@Id
private Long id;
private String name;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建Dao
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import cn.wechar.elasticsearch.entity.User;
@Component
public interface UserDao extends ElasticsearchRepository<User,Long>{
List<User> findByNameLike(String name,Pageable pageable);
}
附dao语法:
Controller测试
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.wechar.elasticsearch.dao.FrScanStatisticsDao;
import cn.wechar.elasticsearch.dao.UserDao;
import cn.wechar.elasticsearch.entity.FrScanStatistics;
import cn.wechar.elasticsearch.entity.User;
@RestController
public class UserController {
@Autowired
UserDao userDao;
@Autowired
FrScanStatisticsDao frScanStatisticsDao;
//保存
@RequestMapping("/save")
public String save(@RequestBody User user) {
System.out.println(user.getId());
userDao.save(user);
return "success";
}
//搜索
@RequestMapping("/searchName")
@CrossOrigin
public List<FrScanStatistics> searchName(String name) {
// 构建查询条件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本分词查询
queryBuilder.withQuery(QueryBuilders.matchQuery("name", name));
// 添加分页查询
queryBuilder.withPageable(PageRequest.of(0, 5));
//Page<User> search = userDao.search(queryBuilder.build());
Page<FrScanStatistics> search = frScanStatisticsDao.search(queryBuilder.build());
//List<User> findByName = userDao.findByNameLike(QueryParser.escape(name).trim().replace(" ",""),PageRequest.of(0, 5));
return search.getContent();
}
}