|
@@ -0,0 +1,75 @@
|
|
|
+import { Client } from '@elastic/elasticsearch';
|
|
|
+import { Provide, Config, Init, Inject } from '@midwayjs/core';
|
|
|
+import { Context } from '@midwayjs/koa';
|
|
|
+import { floor, get, head } from 'lodash';
|
|
|
+
|
|
|
+@Provide()
|
|
|
+export class ContactSearchService {
|
|
|
+ @Config('elasticsearch')
|
|
|
+ esConfig: object;
|
|
|
+ @Inject()
|
|
|
+ ctx: Context;
|
|
|
+ /**es连接实例 */
|
|
|
+ esClient: Client;
|
|
|
+ @Init()
|
|
|
+ async initClient() {
|
|
|
+ const esClient = new Client(this.esConfig);
|
|
|
+ this.esClient = esClient;
|
|
|
+ }
|
|
|
+
|
|
|
+ async search(keyword: string, config: object) {
|
|
|
+ const index = get(config, 'index');
|
|
|
+ const fields = get(config, 'fields', []);
|
|
|
+ const user_id = get(this.ctx, 'user.id');
|
|
|
+ // 添加条件: 当前用户, status:'1'(已审核)
|
|
|
+ const searchObject = {
|
|
|
+ index,
|
|
|
+ query: {
|
|
|
+ bool: {
|
|
|
+ must: [
|
|
|
+ {
|
|
|
+ multi_match: {
|
|
|
+ query: keyword,
|
|
|
+ fields,
|
|
|
+ },
|
|
|
+ },
|
|
|
+ {
|
|
|
+ match_phrase: { status: '1' },
|
|
|
+ },
|
|
|
+ {
|
|
|
+ match_phrase: { user: user_id },
|
|
|
+ },
|
|
|
+ ],
|
|
|
+ },
|
|
|
+ },
|
|
|
+ from: 0,
|
|
|
+ size: 1,
|
|
|
+ };
|
|
|
+ const result = await this.esClient.search(searchObject);
|
|
|
+ const returnData = this.dealResponses(result);
|
|
|
+ // 查找,是否有推荐度为4或4以上的数据.
|
|
|
+ const data = head(get(returnData, 'data', []));
|
|
|
+ if (!data) return false;
|
|
|
+ else {
|
|
|
+ const recommend = get(data, '_recommend', 0);
|
|
|
+ return recommend >= 4;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ dealResponses(result) {
|
|
|
+ const total = get(result, 'hits.total.value', 0);
|
|
|
+ const hits = get(result, 'hits.hits', []);
|
|
|
+ const list = [];
|
|
|
+ for (const ol of hits) {
|
|
|
+ const _score = get(ol, '_score', 0);
|
|
|
+ const data = get(ol, '_source', {});
|
|
|
+ let recommend = 0;
|
|
|
+ /**推荐星数计算:超过5,就都是5颗星.未超过5的都向下取整 */
|
|
|
+ if (_score >= 5) recommend = 5;
|
|
|
+ else recommend = floor(_score);
|
|
|
+ data._recommend = recommend;
|
|
|
+ list.push(data);
|
|
|
+ }
|
|
|
+ return { total, data: list };
|
|
|
+ }
|
|
|
+}
|