SpringBoot整合ElasticSearch搜索引擎之一

本文介绍如何在Spring Boot项目中集成Elasticsearch,并通过示例代码展示配置过程及基本CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值