项目地址:https://gitee.com/diannaodongshizhang/elastic-search
采用注解的方式实现所需功能
pom.xml只需要elasticsearch以及web的就可以了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Config
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.moer.elasticsearch.repository")
@ComponentScan(basePackages = {"com.moer.elasticsearch"})
public class Config extends AbstractElasticsearchConfiguration {
@Value("${elasticsearch.url}")
public String elasticsearchUrl;
@Override
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration config = ClientConfiguration.builder()
.connectedTo(elasticsearchUrl)
.build();
return RestClients.create(config).rest();
}
}
es-settings.json
{
"index": {
}
}
Person
@Document(indexName = Indices.PERSON_INDEX)
@Setting(settingPath = "static/es-settings.json")
public class Person {
@Id
@Field(type = FieldType.Keyword)
private String id;
@Field(type = FieldType.Text)
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PersonRepository
public interface PersonRepository extends ElasticsearchRepository<Person,String> {
}
PersonService
@Service
public class PersonService {
private final PersonRepository repository;
@Autowired
public PersonService(PersonRepository repository) {
this.repository = repository;
}
public void save(final Person person){
repository.save(person);
}
public Person findById(final String id){
return repository.findById(id).orElse(null);
}
}
访问查看Person索引以及存入es数据
http://localhost:9200/person/.
http://localhost:9200/person/_search.