1、ElasticSearch
Elasticsearch是一個基於Apache Lucene(TM)的開源搜索引擎。無論在開源還是專有領域,Lucene可以被認爲是迄今爲止最先進、性能最好的、功能最全的搜索引擎庫。
2、添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3、創建ElasticSearchConfig
@Configuration
@EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
public class ElasticsearchConfig2 {
private String hostname = "127.0.0.1";
private int port = 9300;
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
}
@Bean
public Client client() {
TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(hostname, port);
client.addTransportAddress(address);
return client;
}
}
4、創建Controller
@RestController
@RequestMapping(value="/data/elasticsearch/news")
public class NewsController {
@Autowired
private NewsService newsService;
/**
* 初始化
* @param request
*/
@RequestMapping(value = "/init", method = RequestMethod.POST)
public void init(HttpServletRequest request) {
this.newsService.init();
}
/**
* findAll
* @param request
* @return
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public Map<String, Object> findList(HttpServletRequest request) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("items", this.newsService.findAll());
return params;
}
/**
* find
* @param request
* @return
*/
@RequestMapping(value = "/{title}", method = RequestMethod.GET)
public Map<String, Object> search(@PathVariable String title) {
// 構建查詢條件
QueryBuilder queryBuilder = QueryBuilders.queryString(title);
Map<String, Object> params = new HashMap<String, Object>();
params.put("items", this.newsService.search(queryBuilder));
return params;
}
}