access官方下载 免费完整版 使用Docker和Elasticsearch搭建全文本搜索引(10)

电脑杂谈  发布时间:2018-02-22 15:22:17  来源:网络整理

}

},

...

]

}

}

Elasticsearch HTTP接口对于测试数据是否正常插入很有用,但是如果直接暴露给web应用就很危险。不应该将操作性API功能(例如直接添加和删除文档)直接暴露给应用,而应该写一段简单Node.js API接收客户端请求,(通过私网)转发给Elasticsearch进行查询。

5.1 请求脚本

这一节介绍如何从Node.js应用中向Elasticsearch中发送请求。首先创建新文件:server/search.js。

const{ client, index, type } = require( './connection')

module.exports = {

/** Query ES index for the provided term */

queryTerm (term, offset = 0) {

constbody = {

from: offset,

query: { match: {

text: {

query: term,

operator: 'and',

fuzziness: 'auto'

} } },

highlight: { fields: { text: {} } }

}

returnclient.search({ index, type, body })

}

}

本模块定义了一个简单的search功能,使用输入信息进行匹配查询。详细字段解释如下:

from:为结果标出页码。每次查询默认返回10个结果;因此指定from为10,可以直接显示10-20的查询结果。

query:具体查询关键词。

operator:具体查询操作;本例中采用“and”操作符,优先显示包含所有查询关键词的结果。

fuzziness:错误拼写修正级别(或者是模糊查询级别),默认是2。数值越高,允许模糊度越高;例如数值1,会对Patricc的查询返回Patrick结果。

highlights:返回额外信息,其中包含HTML格式显示匹配文本信息。

可以调整这些参数看看具体的显示信息,可以查看Elastic Full-Text Query DSL[1]获得更多信息。

6. API

本节提供前端代码访问的HTTP API。

6.0 API Server

修改server/app.js内容如下:

constKoa = require( 'koa')

constRouter = require( 'koa-router')

constjoi = require( 'joi')

constvalidate = require( 'koa-joi-validate')

constsearch = require( './search')

constapp = newKoa()

constrouter = newRouter()

// Log each request to the console

app.use( async(ctx, next) => {

conststart = Date.now()

awaitnext()

constms = Date.now() - start

console.log( `${ctx.method}${ctx.url}- ${ms}`)

})

// Log percolated errors to the console

app.on( 'error', err => {

console.error( 'Server Error', err)

})

// Set permissive CORS header


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-88976-10.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...