1.首先,我们创建一个Express应用程序!我将使用express.js生成器。
npm install -g express-generator express ./autocompleter cd autocompleter npm install
2.让我们准备elasticsearch。下载elasticsearch,并将其解压到文件系统的某个位置。然后运行
cd locationOfElasticsearch
bin/elasticsearch (OR bin/elasticsearch.bat on windows).
3.这样做会使用默认参数初始化elasticsearch(localhost上的端口9200是默认配置,稍后我们将需要它)。
现在,我将把elasticsearch npm包添加到之前创建的express.js应用程序中:
npm install elasticsearch --save
这将在package.json中添加以下行:
"elasticsearch": "^9.0.2"
4.elasticsearch模块
我将创建一个将在需要时导入的elasticsearch模块。首先,我将在module创建elasticsearch.js:
添加
var elasticsearch = require('elasticsearch'); var elasticClient = new elasticsearch.Client({ host: 'localhost:9200' }); var indexName = "documents"; function getSuggestions(input) { return elasticClient.search({ index: indexName, body: { query: { match:{ title: input, } } } })// .then(function (response) { // var hits = response.hits.hits; // console.log(response); // }); } exports.getSuggestions = getSuggestions;
5.我现在已经准备好了elasticsearch。转移到Express.js!
首先,我正在为文档路由创建一个端点。我在./routes中创建一个新的文件documents.js,如下所示:
var express = require('express'); var router = express.Router(); var elastic = require('../elasticsearch'); /* GET suggestions */ router.get('/suggest/:input', function (req, res, next) { elastic.getSuggestions(req.params.input).then(function (result) { res.json(result) }); }); /* POST document to be indexed */ router.post('/', function (req, res, next) { elastic.addDocument(req.body).then(function (result) { res.json(result) }); }); module.exports = router;
6.使用承诺,我将弹性搜索的结果路由到response.json(data)函数。这将直接向用户输出从elasticsearch提供的JSON。
不要忘了把这行添加到app.js(在其他已经定义的路由之后,或者也许是:-))
var documents = require('./routes/documents'); //...... app.use('/documents', documents);
7.创建一个为documents的索引 如下:
127.0.0.1:9200/documents //端口 { "settings":{ "number_of_shards":4, "number_of_replicas":2 }, "mappings":{ "suggest":{ "properties":{ "title":{ "type":"text" }, "content":{ "type":"text" }, "suggert":{ "type":"completion", "analyzer":"simple", "search_analyzer":"simple", "preserve_separators":true } } } } }
8.插入数据如下工具postman
127.0.0.1:9200/documents/suggest/1 { "title":"hit", "content":"hit", "suggest":"hit" }
9.前端如下:
function searchds(){ let searchs = $("#search").val(); $.get('documents/suggest/'+searchs,function(rs){ console.log(rs.hits.hits[0]._source); }) } <form class="navbar-form navbar-left" id="searchForm" role="search"> <div class="form-group"> <input type="text" id="search" name="search" class="form-control" placeholder="Search"> </div> <button type="button" class="btn btn-default" οnclick="searchds()">搜索</button> </form>