Node + Elasticseach基本使用

2021-03-11  本文已影响0人  南城忆往

elastic-builder官方地址

const express = require('express');
const router = express.Router();
# ES地址、索引配置
const esHosts = require('../setting.js').esHosts;
const esIndex = require('../setting.js').esIndex;
const elasticSearch = require('elasticsearch');
# query模版工具
const esb = require('elastic-builder'); //the builder
// 初始化ES
const client = elasticSearch.Client({
    hosts: esHosts,
    log: 'trace',  // 生产环境注释
    // sniffOnStart: true,
    // sniffInterval: 60000,
    // keepAliveInterval: 6000,
    // auth: {
    //     username: process.env.ES_USERNAME,
    //     password: process.env.ES_PASSWORD
    // },
    apiVersion: '7.3' // 生产环境注意版本
});


/***
 * 根据Id查询消息详情
 */
router.get('/api/msg/:id', async function (req, res, next) {
    client.get({
        index: esIndex,
        id: req.params.id
    }).then(function (resp) {
        res.json({row: resp})
    },function (err) {
        console.trace(err.message);
        res.status(500).json({message: err.message});
    });
});

/***
 * 查询消息
 * 条件查询、时间区间查询
 */
router.post('/api/msg/query', async function (req, res, next) {
    let size = req.query.pageSize;
    let from = (req.query.pageNo - 1) * req.query.pageSize;
    const requestBody = esb.requestBodySearch();
    // 条件查询
    let queryModel = [];
    if (req.body.category){
        queryModel.push(esb.matchQuery("category", req.body.category));
    }
    if (req.body.service) {
        queryModel.push(esb.matchQuery("service", req.body.service));
    }
    if (req.body.instance) {
        queryModel.push(esb.matchQuery("instance", req.body.instance));
    }
    if (req.body.time) {
        queryModel.push(esb.rangeQuery('time').gte(req.body.time[0]).lte(req.body.time[1]));
    }
    requestBody.query(esb.boolQuery().filter(queryModel))
        .size(size)
        .from(from);
    await client.search({
        index: esIndex,
        body: requestBody.toJSON()
    }).then(function (resp) {
        res.json({table: resp.hits.hits, total: parseInt(resp.hits.total.value)})
    }, function (err) {
        console.trace(err.message);
        res.status(500).json({message: err.message});
    });
});


module.exports = router;
上一篇下一篇

猜你喜欢

热点阅读