node使用elasticsearch模块实现简单检索

安装

npm i elasticsearch
  • 代码
const elasticsearch = require('elasticsearch');

const client = new elasticsearch.Client({
    host: "192.168.2.3:9200",
});
//传入es索引名称和搜索的字符串
async function query(es_index, query_str) {
    let querystr = {
        index: es_index,
        type: '_doc',
        // from: page * size,
        // size: size,
        body: {
        //只返回name和value字段
            _source: [
                "id", "name", "value"
            ],
            query: {
                bool: {
                    must: {
                        multi_match: {    //匹配name和value
                            query: query_str,
                            fields: ["name", "value"]
                        }
                    }
                }
            }
        }

    };
    let response = await client.search(querystr);
    //遍历出name和value,不返回父节点_source
    let results = response.hits.hits.map(v =>{
        return {
            id:v._source.id,
            name:v._source.name,
            value:v._source.value
        };
    });
   return results;
}

你可能感兴趣的:(node使用elasticsearch模块实现简单检索)