Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

【搜索】elasticsearch

  • 安装

    npm i -S @elastic/elasticsearch
    
    • 最新版本 7.16.0
      • 要求node版本要在12.0以上
  • lib/db文件夹下,新建elastic_core.js文件,进行封装

    import { Client } from '@elastic/elasticsearch';
    import config from "config";
    import { Log } from "../utils/api_log.js";
    const log = new Log("elastic_core");
    
    const client = new Client({ node: config.get('elasticConfig.url') })
    
    client.on('error', (err) =>{
        log.error('elastic client err:', err);
    })
    
    const hitsFilter = (hit, fieldsArray) => {
        const filtered = {};
        filtered.score = hit._score;
        fieldsArray.forEach((field) => {
            if (hit._source[field]) {
                filtered[field] = hit._source[field];
            }
        });
        return filtered;
    }
    
    export const elasticSearch = async (obj, fieldsArray) => {
        const { body } = await client.search(obj);
        return {
            total: body.hits.total.value,
            hits: body.hits.hits.map((hit)=>{
                return hitsFilter(hit, fieldsArray);
            })
        };
    }
    
    //这里可添加下面的测试代码,只运行一次即可生成测试数据,后面要注释掉
    
    • 需要配置url,默认是http://127.0.0.1:9200
  • 封装后在路由中使用

    import { elasticSearch } from "../../../db/elastic_core.js";
    
    router.get("/test_elastic", async ctx => {
        log.debug("== get test_elastic")
        const fieldsArray = ["character", "quote"];
        const result = await elasticSearch({
            index: 'game-of-thrones',
            body: {
                query: {
                    match: { quote: 'winter' }
                }
            }
        }, fieldsArray)
        ctx.body = result;
    })
    
  • 测试代码

    await client.index({
        index: 'game-of-thrones',
        body: {
            character: 'Ned Stark',
            quote: 'Winter is coming.'
        }
    })
    
    await client.index({
        index: 'game-of-thrones',
        body: {
            character: 'Daenerys Targaryen',
            quote: 'I am the blood of the dragon.'
        }
    })
    
    await client.index({
        index: 'game-of-thrones',
        body: {
            character: 'Tyrion Lannister',
            quote: 'A mind needs books like a sword needs a whetstone.'
        }
    })
    
    await client.indices.refresh({ index: 'game-of-thrones' })