elasticsearch基於smartcn中文分詞查詢

咱們新建索引film2java

而後映射的時候,指定smartcn分詞;app

 

post  http://192.168.1.111:9200/film2/_mapping/dongzuo/post

{ui

    "properties": {url

        "title": {spa

            "type": "text",.net

"analyzer": "smartcn"code

        },索引

        "publishDate": {ci

            "type": "date"

        },

        "content": {

            "type": "text",

"analyzer": "smartcn"

        },

        "director": {

            "type": "keyword"

        },

        "price": {

            "type": "float"

        }

    }

}

 

而後執行前面的數據代碼;

 

這樣前面film索引,數據是標準分詞,中文所有一個漢字一個漢字分詞;film2用了smartcn,根據內置中文詞彙分詞;

 

咱們用java代碼來搞分詞搜索;

 

先定義一個靜態常量:

private static final String ANALYZER="smartcn";

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/**

 * 條件分詞查詢

 @throws Exception

 */

@Test

public void search()throws Exception{

    SearchRequestBuilder srb=client.prepareSearch("film2").setTypes("dongzuo");

    SearchResponse sr=srb.setQuery(QueryBuilders.matchQuery("title""星球狼").analyzer(ANALYZER))

        .setFetchSource(new String[]{"title","price"}, null)

        .execute()

        .actionGet(); 

    SearchHits hits=sr.getHits();

    for(SearchHit hit:hits){

        System.out.println(hit.getSourceAsString());

    }

}

指定了 中文分詞,查詢的時候 查詢的關鍵字先進行分詞 而後再查詢,不指定的話,默認標準分詞;

 

這裏再講下多字段查詢,好比百度搜索,搜索的不單單是標題,還有內容,因此這裏就有兩個字段;

咱們使用 multiMatchQuery 咱們看下Java代碼:‘’

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/**

 * 多字段條件分詞查詢

 @throws Exception

 */

@Test

public void search2()throws Exception{

    SearchRequestBuilder srb=client.prepareSearch("film2").setTypes("dongzuo");

    SearchResponse sr=srb.setQuery(QueryBuilders.multiMatchQuery("非洲星球""title","content").analyzer(ANALYZER))

        .setFetchSource(new String[]{"title","price"}, null)

        .execute()

        .actionGet(); 

    SearchHits hits=sr.getHits();

    for(SearchHit hit:hits){

        System.out.println(hit.getSourceAsString());

    }

}

相關文章
相關標籤/搜索