自定义 Mapping 的建议
- 创建一个临时的索引,写入一些样本数据;
- 通过 API 查看该索引的 Dynamic Mapping;
- 在次基础上修改 Mapping;
- 使用修改好的 Mapping 创建新的索引;
- 删除临时索引;
控制字段是否被索引
创建索引 users
- 字段 mobile 将无法被索引,意味着:mobile 字段无法被搜索,而且节省了很多磁盘开销;
DELETE users
PUT users
{
"mappings" : {
"properties" : {
"firstName" : {
"type" : "text"
},
"lastName" : {
"type" : "text"
},
"mobile" : {
"type" : "text",
"index": false
}
}
}
}
倒排索引 | 配置 | 4 个级别
- docs - 记录 doc id;
- freqs - 记录 doc id / term frequencies;
- positions - 记录 doc id / term frequencies / term positions;
- offsets - 记录 doc id / term frequencies / term positions / character offsets;
Text 类型默认记录级别是 positions,其他默认为 docs,记录内容越多,占用空间越大;
对文档中的 null 值的搜索
创建索引 users
- mobile 字段设置为
"null_value": "NULL"
;
DELETE users
PUT users
{
"mappings" : {
"properties" : {
"firstName" : {
"type" : "text"
},
"lastName" : {
"type" : "text"
},
"mobile" : {
"type" : "keyword",
"null_value": "NULL"
}
}
}
}
插入数据
- id 为 2 的文档的 mobile 字段为 null 值;
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming",
"mobile": null
}
PUT users/_doc/2
{
"firstName":"Ruan2",
"lastName": "Yiming2"
}
搜索 null 值
GET users/_search
{
"query": {
"match": {
"mobile":"NULL"
}
}
}
copy_to 的设置
- _all 在 7 中被 copy_to 替代;
- 满足一些特定的搜索需求;
- copy_to 将字段的数值拷贝到目标字段,实现类似 _all 的作用;
- copy_to 的目标字段不出现在 _source 中;
创建索引
DELETE users
PUT users
{
"mappings": {
"properties": {
"firstName":{
"type": "text",
"copy_to": "fullName"
},
"lastName":{
"type": "text",
"copy_to": "fullName"
}
}
}
}
写入新文档
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming"
}
搜索目标字段
GET users/_search?q=fullName:(Ruan Yiming)
数组类型
- ElasticSearch 中不提供专门的数组类型;
- 但是任何字段,都可以包含多个相同类型的数值;
新增用户
PUT users/_doc/1
{
"name":"onebird",
"interests":"reading"
}
PUT users/_doc/1
{
"name":"twobirds",
"interests":["reading","music"]
}
搜索用户
POST users/_search
{
"query": {
"match_all": {}
}
}
查看索引的 Mapping
- interests 的 type 还是 text;
GET users/_mapping