1. 程式人生 > >Spring boot 整合 Elasticsearch

Spring boot 整合 Elasticsearch

引入依賴

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!--SpringBoot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</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-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <!--elasticsearch-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.1.1</version>
        </dependency>
        <!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!-- lombok簡化註解 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>
        <!-- 阿里FastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
    </dependencies>

新增配置檔案application.properties

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.local=false
spring.data.elasticsearch.repositories.enabled=true

entity類

/**
 * @author 向振華
 * @date 2018/11/21 15:48
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
//es註解,設定索引名稱以及型別
@Document(indexName = "xzhes", type = "info")
public class EsEntity {

    //id(需要新增@Id註解,或會自動識別名稱為id的欄位為id,其餘欄位沒有限制)
    @Id
    private Integer id;
    //名稱
    private String name;
    //性別
    private String sex;
    //年齡
    private Integer age;

}

Repository類

/**
 * @author 向振華
 * @date 2018/11/21 16:53
 */
public interface EsRepository extends ElasticsearchRepository<EsEntity, Integer> {
}

service類

/**
 * @author 向振華
 * @date 2018/11/21 15:54
 */
public interface EsService {

    void save(EsEntity esEntity);

    List<EsEntity> select(Search search);

}
/**
 * @author 向振華
 * @date 2018/11/22 10:08
 */
@Service
public class EsServiceImpl implements EsService {

    @Resource
    private EsRepository esRepository;

    @Override
    public void save(EsEntity esEntity) {
        esRepository.save(esEntity);
    }

    @Override
    public List<EsEntity> select(Search search) {

        //建立builder
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder下有must、should以及mustNot 相當於sql中的and、or以及not
        //設定“名稱”模糊搜尋
        if (search.getName()!=null) {
            builder.must(QueryBuilders.matchPhraseQuery("name", search.getName()));
        }
        //設定“性別”
        if (search.getSex()!=null) {
            builder.must(new QueryStringQueryBuilder(search.getSex()).field("sex"));
        }
        //按照年齡從高到低
        FieldSortBuilder sort = SortBuilders.fieldSort("age").order(SortOrder.DESC);
        //設定分頁(拿第一頁,一頁顯示兩條)。注意!es的分頁api是從第0頁開始的(坑)
        PageRequest page = new PageRequest(0, 2);

        //構建查詢
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //將搜尋條件設定到構建中
        nativeSearchQueryBuilder.withQuery(builder);
        //將分頁設定到構建中
        nativeSearchQueryBuilder.withPageable(page);
        //將排序設定到構建中
        nativeSearchQueryBuilder.withSort(sort);
        //生產NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();

        //執行
        Page<EsEntity> searchs = esRepository.search(query);

        //獲取總條數(前端分頁需要使用)
        int total = (int) searchs.getTotalElements();

        //獲取查詢到的資料內容
        List<EsEntity> content = searchs.getContent();

        return content;
    }
}

搜尋實體類

/**
 * @author 向振華
 * @date 2018/11/22 11:02
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Search {
    //名稱
    @ApiModelProperty(value = "名稱")
    private String name;

    //性別
    @ApiModelProperty(value = "性別")
    private String sex;

    //年齡
    @ApiModelProperty(value = "年齡")
    private Integer age;
}

測試controller

/**
 * @author 向振華
 * @date 2018/11/21 16:05
 */
@Api(tags = "測試")
@RequestMapping("test")
@RestController
public class TestController {

    @Resource
    private EsService esService;

    @ResponseBody
    @GetMapping("/add")
    public String add(EsEntity esEntity) {
        esService.save(esEntity);
        return "success";
    }

    @ResponseBody
    @GetMapping("/select")
    public String select(Search search) {
        List<EsEntity> entities = esService.select(search);
        return JSON.toJSONString(entities);
    }
}

啟動類

/**
 * 啟動類(需要先啟動elasticsearch.bat)
 * @author 向振華
 * @date 2018/11/21 15:16
 */
@SpringBootApplication
public class ApplicationMain {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class, args);
    }
}

 

注意:

1.啟動專案之前需要先啟動elasticsearch.bat。

2.可以用chrome瀏覽器裝elasticsearch head外掛進行檢視。

3.elasticsearch下載地址:https://www.elastic.co/downloads/elasticsearch

4.本專案地址:https://github.com/xxiangzh/es-server