elasticsearch基于smartcn中文分词查询

我们新建索引film2

然后映射的时候,指定smartcn分词;

 

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

{

    "properties": {

        "title": {

            "type": "text",

"analyzer": "smartcn"

        },

        "publishDate": {

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

    }

}

转载于:https://my.oschina.net/u/3004242/blog/1809033

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值