一、添加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条文档,打印数组长度、依次遍历: