Elasticsearch的Javascript Client使用指南

一、添加js库

​ 使用Elasticsearch Javascript API需要两个JS库的支持,一个是JQuery[下载地址:http://www.jq22.com/jquery/jquery-1.8.3.zip],一个是elasticsearch.js[下载地址:https://download.elasticsearch.org/elasticsearch/elasticsearch-js/elasticsearch-js-14.0.0.zip]。新建HTML页面并导入以上两个库:

<script type="text/javascript" src="scripts/jquery-1.8.0.min.js"></script>
<script type='text/javascript' src='scripts/elasticsearch.jquery.min.js'></script>

二、创建client

创建client:

var client = new $.es.Client({
    hosts: 'http://10.90.1.64:9200'
});

测试client是否创建成功:

client.ping({
    requestTimeout: 30000,
}, function (error) {
    if (error) {
        console.error('elasticsearch cluster is down!');
    } else {
        console.log('All is well');
    }
});

三、执行搜索

准备一个RESTFul的Query:


GET  spnews/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "title": {
              "value": "足球"
            }
          }
        },{
        "range": {
          "postdate": {
            "gte": "2016-01-01 00:00:00"
          }
        }
        }
      ]
    }
  }
}

在js中的等价表示:

client.ping({
    requestTimeout: 30000,
}, function (error) {
    if (error) {
        console.error('elasticsearch cluster is down!');
    } else {
        console.log('All is well');
    }
});

client.search({
    index: 'spnews',
    type: 'news',
    body: {
        query: {
            bool: {
                must: [{
                    term: {
                        title: '足球'
                    }
                }, {
                    range: {
                        postdate: {
                            gte: '2016-01-01 10:00:00',
                            format: 'yyyy-MM-dd HH:mm:ss'
                        }
                    }
                }]
            }
        }
    }
}).then(function (resp) {
    var hits = resp.hits.hits;

    console.log(hits.length);


    for (var i  in hits) {
        console.log(hits[i]);
    }

}, function (err) {
    console.trace(err.message);
});

查询结果在resp.hits.hits数组中, 默认返回10条文档,打印数组长度、依次遍历:

这里写图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

esc_ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值