测试 ik 分词器
get _analyze
{
"text":"中华人民共和国国歌",
"analyzer":"ik_smart"
}
执行结果:
{
"tokens" : [
{
"token" : "中华人民共和国",
"start_offset" : 0,
"end_offset" : 7,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "国歌",
"start_offset" : 7,
"end_offset" : 9,
"type" : "CN_WORD",
"position" : 1
}
]
}
与之前的结果不同,这才是中文分词的结果
创建索引指定映射
在创建映射时,指定分词器
PUT /toutiao_v2
{
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "ik_smart", // 指定 最粗粒度分词器
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"content": {
"type": "text",
"analyzer": "ik_smart" // 指定 最粗粒度分词器
},
"author": {
"type": "keyword"
},
"like": {
"type": "integer"
},
"date": {
"type": "date"
}
}
}
}
添加测试数据
POST /toutiao_v2/_doc
{
"title":"共同富裕",
"content":"共同富裕"
}
POST /toutiao_v2/_doc
{
"title":"新中华共和国",
"content":"人民共和国"
}
POST /toutiao_v2/_doc
{
"title":"中华共和国",
"content":"中华人民共和国"
}
查询
查询一个词
GET /toutiao_v2/_search
{
"query":{
"match":{
"title":"共和国"
}
}
}
共和国 是一个词,所以能查询出 包含这两个词 的结果,而不是包含 共、和、国 这三个字的结果,结果如下:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 0.6931471,
"hits" : [
{
"_index" : "toutiao_v2",
"_type" : "_doc",
"_id" : "ZhVnw4QBMLEbHcToBDno",
"_score" : 0.6931471,
"_source" : {
"title" : "中华共和国",
"content" : "中华人民共和国"
}
},
{
"_index" : "toutiao_v2",
"_type" : "_doc",
"_id" : "XRVmw4QBMLEbHcTovTkQ",
"_score" : 0.5754429,
"_source" : {
"title" : "新中华共和国",
"content" : "人民共和国"
}
}
]
}
}
查询 共和
由于是指定映射时,指定最粗粒度的分词器:ik_smart ,所以 共和 不是一个词
GET /toutiao_v2/_search
{
"query":{
"match":{
"title":"共和"
}
}
}