Elasticsearch的Javascript Client使用指南
Posted esc_ai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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条文档,打印数组长度、依次遍历:
以上是关于Elasticsearch的Javascript Client使用指南的主要内容,如果未能解决你的问题,请参考以下文章
ElasticHD —— ElasticSearch 的可视化应用 | 软件推介