angular 2中elasticsearch.js的使用

版权声明:.net/web/医疗技术的木子纵横的个人分享 https://blog.csdn.net/muzizongheng/article/details/85246868
1.安装
进入angular工程中, 执行
npm install --save elasticsearch


2.封装api

import { Injectable } from '@angular/core';
import { Client, SearchResponse } from 'elasticsearch';
import { Observable } from 'rxjs/rx';

@Injectable()
export class ElasticSearchService {

private _client: Client;

constructor() {
if (!this._client) {
this.connect();
}
}

private connect(): void {
this._client = new Client({
log: 'trace'
});
}

isAvailableAsync(): Observable<SearchResponse<{}>> {
return Observable.fromPromise(<Promise<SearchResponse<{}>>> this._client.ping({
requestTimeout: Infinity
}));
}

searchAsync(value: any): Observable<SearchResponse<{}>> {
if (value) {

console.log(value);

return Observable.fromPromise(<Promise<SearchResponse<{}>>>
this._client.search({index: '.kibana', method: 'get', body: null}));
}
}

isAvailable(): any {
return this._client.ping({
requestTimeout: Infinity
});
}

search(value: any): any {
if (value) {

console.log(value);

return this._client.search({index: '.kibana', method: 'get'});

}
}

}

3.遇到的报错:
a. Error: Request error, retrying   POST http://localhost:9200/.kibana/_search => Request failed to complete

上面原因是POST方法,应该改为GET

Elasticsearch ERROR: 
Error: Request error, retrying -- connect ECONNREFUSED 127.0.0.1:9200
at Log.error (/usr/src/project/node_modules/elasticsearch/src/lib/log.js:225:56)


Elasticsearch WARNING: 
Unable to revive connection: http://localhost:9200/

Elasticsearch WARNING: 
No living connections

Error: No Living connections
at sendReqWithConnection (../node_modules/elasticsearch/src/lib/transport.js:210:15)
at next (../node_modules/elasticsearch/src/lib/connection_pool.js:213:7)

上面原因是跨域问题, 把elasticsearch服务停掉,取es的安装目录里的elasticsearch.yml配置文件中添加如下配置, 然后重新启动es的服务

解决跨域的配置项
http.cors.enabled : true
http.cors.allow-origin : "*"
http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length


注意事项:
a,可以把默认的promise封装为Observable接口, 具体实现方式是Async结尾的2个函数, 通过 Observable.fromPromise 做了转换
b.默认的es提供的search的http请求访问为post, 我们根据情况是否指定为GET
c.需要注意跨域访问问题,不然会报错,此时要结合浏览器和es client的trace log综合分析





参考:

猜你喜欢

转载自blog.csdn.net/muzizongheng/article/details/85246868