1. 程式人生 > >SpringBoot整合Elasticsearch入門案例

SpringBoot整合Elasticsearch入門案例

前提:

    首先,你的Elasticsearch,kibana已經安裝,並且已經啟動了。

專案結構:

 pom.xml:需要引入elasticsearch與spring boot的整合包,lombok這個包是可以用註解代替get、set、tostring....等方法。

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>

實體類:

package com.lucifer.elasticsearch.pojo;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @author: Lucifer
 * @create: 2018-11-18 18:59
 * @description:
 **/
@Data
@Document(indexName = "lucifer",type = "item",shards = 1)
public class Item {

    @Field(type = FieldType.Long)
    @Id
    Long id;

    @Field(type = FieldType.Text,analyzer = "ik_smart")
    String title; //標題

    @Field(type = FieldType.Keyword)
    String category;// 分類

    @Field(type = FieldType.Keyword)
    String brand; // 品牌

    @Field(type = FieldType.Double)
    Double price; // 價格

    @Field(type = FieldType.Keyword)
    String images; // 圖片地址
}

application.yml: 

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 192.168.59.136:9300

測試類: 建立索引庫及新增對映關係。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchApplicationTests {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void testCreate() {
        //建立索引庫
        elasticsearchTemplate.createIndex(Item.class);

        //對映關係
        elasticsearchTemplate.putMapping(Item.class);
    }

}

啟動測試類,然後訪問瀏覽器http://192.168.59.136:5601

 

建立介面:ItemRepository

package com.lucifer.elasticsearch;

import com.lucifer.elasticsearch.pojo.Item;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;

public interface ItemRepository extends ElasticsearchCrudRepository<Item,Long> {
}

 實體類中新增以下兩個註解,建立構造方法。

@AllArgsConstructor
@NoArgsConstructor

測試類中,新增批量新增方法。

   //批量新增
    @Test
    public void insertIndex(){
        List<Item> list=new ArrayList<>();
        list.add(new Item(1L,"小米手機8","手機","小米",2700.00,"http://image.lucifer.com/1111.jpg"));
        list.add(new Item(2L,"榮耀手機8","手機","華為",3500.00,"http://image.lucifer.com/2222.jpg"));
        list.add(new Item(3L,"蘋果手機8","手機","蘋果",7500.00,"http://image.lucifer.com/3333.jpg"));
        list.add(new Item(4L,"oppoR11","手機","OPPO",2999.00,"http://image.lucifer.com/4444.jpg"));
        itemRepository.saveAll(list);

    }

啟動測試類批量新增方法,然後訪問瀏覽器http://192.168.59.136:5601

 

測試查詢:

   @Test
    public void testFind(){
        // 查詢全部,並安裝價格降序排序
        Iterable<Item> items = this.itemRepository.findAll(Sort.by(Sort.Direction.DESC, "price"));
        items.forEach(item-> System.out.println(item));
    }

  ps:

 items.forEach(item-> System.out.println(item)); 

是java8的新特性,同:

for(Item item:items){
    System.out.println(item );
}

控制檯列印結果: 並且是按照價格降序排列。

ItemRepository 介面中自定義方法: 

public interface ItemRepository extends ElasticsearchCrudRepository<Item,Long> {
    List<Item> findByPriceBetween(Double begin,Double end);
}

 測試條件查詢:

  @Test
    public void testFindBy(){
        // 查詢兩價格之間
        Iterable<Item> items = this.itemRepository.findByPriceBetween(2000d,5000d);
        for(Item item:items){
            System.out.println(item );
        }

    }

控制檯列印結果: 

 

附:

Spring Data 的另一個強大功能,是根據方法名稱自動實現功能。

比如:你的方法名叫做:findByTitle,那麼它就知道你是根據title查詢,然後自動幫你完成,無需寫實現類。

當然,方法名稱要符合一定的約定:

Keyword Sample Elasticsearch Query String
And findByNameAndPrice {"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
Or findByNameOrPrice {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
Is findByName {"bool" : {"must" : {"field" : {"name" : "?"}}}}
Not findByNameNot {"bool" : {"must_not" : {"field" : {"name" : "?"}}}}
Between findByPriceBetween {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
LessThanEqual findByPriceLessThan {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
GreaterThanEqual findByPriceGreaterThan {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
Before findByPriceBefore {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
After findByPriceAfter {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
Like findByNameLike {"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
StartingWith findByNameStartingWith {"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
EndingWith findByNameEndingWith {"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}
Contains/Containing findByNameContaining {"bool" : {"must" : {"field" : {"name" : {"query" : "**?**","analyze_wildcard" : true}}}}}
In findByNameIn(Collection<String>names) {"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}
NotIn findByNameNotIn(Collection<String>names) {"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}
Near findByStoreNear Not Supported Yet !
True findByAvailableTrue {"bool" : {"must" : {"field" : {"available" : true}}}}
False findByAvailableFalse {"bool" : {"must" : {"field" : {"available" : false}}}}
OrderBy findByAvailableTrueOrderByNameDesc {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}