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());

    }

}

相关文章
相关标签/搜索