Spring Boot 2.0 Spring Data ElasticSearch入門

首先安裝好ElasticSearch胆绊,我安裝的是elasticsearch-5.6.9, 并且安裝了IK中文分詞插件压状。

第一步,pom.xml里添加spring-boot-starter-data-elasticsearch

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-libs-release</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-maven-plugin</artifactId>
                <version>1.16.20.0</version>
            </plugin>
        </plugins>
    </build>

第二步娱两,application.yml里添加如下配置:

spring:
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: localhost:9300

cluster-name 是你安裝的ElasticSearch配置里的集群名稱,cluster-nodes是你安裝的ElasticSearch節(jié)點(diǎn)谷婆,如果有多個(gè)辽聊,以逗號(hào),分隔跟匆。

第三步通砍,創(chuàng)建Document

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = ItemDocument.INDEX, type = ItemDocument.TYPE)
public class ItemDocument {

    public static final String INDEX = "items";
    public static final String TYPE = "item";

    /**
     * 商品唯一標(biāo)識(shí)
     */
    @Id
    @Field(type = FieldType.Keyword)
    private String id;

    /**
     * 類目id
     */
    @Field(type = FieldType.Integer)
    private Integer catId;

    /**
     * 商品名稱
     */
    @Field(type = FieldType.Text, index = false)
    private String name;


    /**
     * 商品價(jià)格
     */
    @Field(type = FieldType.Long)
    private Long price;


    /**
     * 商品的描述
     */
    @Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
    private String description;
}

第四步,創(chuàng)建Repository

public interface ItemDocumentRepository extends ElasticsearchRepository<ItemDocument, String> {
}

第五步

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.example.elasticSearch.repository")
public class ElasticSearchApplication {
    public static void main(String[] args) {
        SpringApplication.run(ElasticSearchApplication.class, args);
    }
}

最后測(cè)試一下

@RestController
@RequestMapping("/items")
public class SearchController {

    @Autowired
    private ItemDocumentRepository repository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping(path = "/{id}")
    public ResponseEntity getItem(@PathVariable("id") String id) {
        ItemDocument com = repository.findById(id).get();
        return new ResponseEntity(com.toString(), HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity createItem(@RequestBody ItemDocument document) {
        repository.save(document);

        return new ResponseEntity(document.toString(), HttpStatus.OK);
    }

    @GetMapping(path = "/singleWord")
    public List<ItemDocument> singleTitle(String word, @PageableDefault Pageable pageable) {
        //使用queryStringQuery完成單字符串查詢
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryStringQuery(word)).withPageable(pageable).build();
        return elasticsearchTemplate.queryForList(searchQuery, ItemDocument.class);
    }

    @GetMapping(path = "/singleWord2")
    public Page<ItemDocument> singleTitle2(String word, @PageableDefault Pageable pageable) {
        //使用queryStringQuery完成單字符串查詢
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(word);
        return repository.search(builder, pageable);
    }
}

創(chuàng)建商品

POST http://localhost:8080/items 

body:
{
   "id":"1",
   "catId":1,
   "description":"商品,質(zhì)量好泡徙,包郵膜蠢,售后服務(wù)保障",
   "name":"商品123",
   "price":1000
}

第二個(gè)商品:
{
   "id":"2",
   "catId":1,
   "description":"商品456,結(jié)實(shí)耐用礁竞,包郵杉辙,售后服務(wù)保障",
   "name":"商品456",
   "price":200
}

查詢商品

GET http://localhost:8080/items/1

搜索商品

GET http://localhost:8080/items/singleWord?word=耐用&size=20

GET http://localhost:8080/items/singleWord2?word=耐用&size=20
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狂男,隨后出現(xiàn)的幾起案子硼端,更是在濱河造成了極大的恐慌,老刑警劉巖县耽,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件镣典,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡澎剥,警方通過(guò)查閱死者的電腦和手機(jī)赶舆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門祭饭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)叙量,“玉大人绞佩,你說(shuō)我怎么就攤上這事寺鸥∑飞剑” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)酸些。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么闯第? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任咳短,我火速辦了婚禮,結(jié)果婚禮上咙好,老公的妹妹穿的比我還像新娘。我一直安慰自己嘹悼,他們只是感情好层宫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布萌腿。 她就那樣靜靜地躺著,像睡著了一般毁菱。 火紅的嫁衣襯著肌膚如雪米死。 梳的紋絲不亂的頭發(fā)上峦筒,一...
    開(kāi)封第一講書(shū)人閱讀 51,482評(píng)論 1 302
  • 那天勘天,我揣著相機(jī)與錄音,去河邊找鬼脯丝。 笑死,一個(gè)胖子當(dāng)著我的面吹牛宠进,可吹牛的內(nèi)容都是我干的晕拆。 我是一名探鬼主播材蹬,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼昆庇!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后乓旗,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡汇跨,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年扰法,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了毅厚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡祠锣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出伴网,到底是詐尸還是另有隱情,我是刑警寧澤沸伏,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布动分,位于F島的核電站,受9級(jí)特大地震影響姆另,放射性物質(zhì)發(fā)生泄漏坟乾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一明吩、第九天 我趴在偏房一處隱蔽的房頂上張望殷费。 院中可真熱鬧,春花似錦宗兼、人聲如沸氮采。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)躯概。三九已至,卻和暖如春娶靡,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背塔鳍。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腔寡,地道東北人掌唾。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像凭语,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子叽粹,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理虫几,服務(wù)發(fā)現(xiàn)挽拔,斷路器,智...
    卡卡羅2017閱讀 134,656評(píng)論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,810評(píng)論 6 342
  • Elastic+logstash+head簡(jiǎn)單介紹 一. 概述 ElasticSearch是一個(gè)基于Lucene的...
    柒月失凄閱讀 4,269評(píng)論 0 4
  • **一、iOS中有三種方式來(lái)實(shí)現(xiàn)正則表達(dá)式的匹配∈趼悖現(xiàn)在將他們都記錄在這里: **1.利用NSPredicate(謂...
    Wang99閱讀 1,004評(píng)論 0 0
  • 小時(shí)候 拼命地想要逃離它 去那盛開(kāi)童話的地方 年輕時(shí) 明明有地方可以歇腳 可偏偏選擇去流浪 中年時(shí) 心心念念想要靠...
    哆啦A念閱讀 133評(píng)論 0 0