



文献 [11] 给出了从创建数据索引、构建映像、录入信息、构建检索表达式、返回检索结果等比较全面的信息检索过程。在得出检索结果后,可将得到的检索结果发送到页面前端,在通过相应的UI渲染后,就能得到类似普通搜索引擎那样的结果了。为方便看到中间结果,下面的例子仍是借助Head插件实现的。
第一步,创建示例索引文件test,注意用PUT方法实现,如图1.13所示。
图1.13 创建索引示例test
第二步,创建数据映像文件,主要代码如代码段1.2所示,处理结果如图1.14所示。注意,本例中采用的是IK分析器。
Tips: 为便于书中表述风格的统一,在下面代码中参照C语言的注释方式增加了注释,但这种注释风格在Head和实际应用环境中是不允许的,这里只是为了方便说明而已。
//代码段1.2:创建数据mapping
{
"news": { //建立news的Type
"properties": { //下面是定义各个字段
"content": { //对content字段的结构设计
"type": "string", //当前字段为字符串类型
"store": "no", //当前字段不存储
"term_analyzer": "with_positions_offsets",
//指示不仅保存分隔后的词还保存词之间的距离
"index_analyzer": "ik", //设定索引时用的分词器是IK分析器
"search_analyzer": "ik" //设定搜索该字段时用的分词器是IK分析器
},
"title": { //对title字段的结构设计
"type": "string",
"store": "no",
"term_analyzer": "with_positions_offsets",
"index_analyzer": "ik",
"search_analyzer": "ik",
"boost": 5
},
"author": { //对author字段的结构设计
"type": "string",
"index": "not_analyzed" //设定该字段为不分词
},
"publish_date": { //对publish_date字段的结构设计
"type": "date",
"format": "yyyy/mm/dd" //设定该日期字段的格式
},
"category": { //对category字段的结构设计
"type": "string",
"index": "not_analyzed"
}
}
}
}
图1.14 创建映像
第三步,录入数据信息。可以在Head中采用如图1.15的方法添加数据。添加数据后,可以在Head中看到数据情况,如图1.16所示。
图1.15 添加数据
图1.16 查看添加好的索引数据
第四步,构建检索表达式,其内容可包括如下几个主要部分:
有关构造检索的示例代码详见代码段1.3(对其中部分代码含义的解释参见第3章)。检索结果如图1.17所示。
//代码段1.3:构建检索表达式
{
"from": 0, //检索结果集合的起始位置
"size": 10, //返回的检索结果数量
"fields": [ //指定检索结果document集合中含有哪些域
"title",
"content",
"publish_date",
"category",
"author"
],
"sort":[ //定义排序方式
{
"publish_date": { //搜索结果按照publish_date进行排序
"order": "asc" //按正序排序,
即从小到大
}
},
"_score" //先按照publish_date,
再按照_score排序
],
"query": {
"bool": { //构建布尔查询
"should": [
{
"term": {
"title": "中国"
}
},
{
"term": {
"content": "中国"
}
}
]
}
},
"filter": { //创建过滤规则
"range": {//按照区间进行过滤
"publish_date": {
"from": "2014/01/01", //起始时间
"to": "2014/12/31", //结束时间
"include_lower": true,
"include_upper": false
}
}
},
"highlight": { //对高亮进行相关设置
"pre_tags": [ //高亮的前置标签
"<tag1>",
"<tag2>"
],
"post_tags": [ //高亮的后置标签
"</tag1>",
"</tag2>"
],
"fields": { //需高亮的域
"title": {},
"content": {}
}
},
"facets": { //构建聚合
"cate": {
"terms": {
"field": "category"
}
}
}
}
图1.17 检索结果