Debian Codegraph @

packages/search/lib/commands/SEARCH.ts

raw
1 import { RedisCommandArguments } from '@redis/client/dist/lib/commands';
2 import { pushSearchOptions, RedisSearchLanguages, Params, PropertyName, SortByProperty, SearchReply } from '.';
3
4 export const FIRST_KEY_INDEX = 1;
5
6 export const IS_READ_ONLY = true;
7
8 export interface SearchOptions {
9 VERBATIM?: true;
10 NOSTOPWORDS?: true;
11 // WITHSCORES?: true;
12 // WITHPAYLOADS?: true;
13 WITHSORTKEYS?: true;
14 // FILTER?: {
15 // field: string;
16 // min: number | string;
17 // max: number | string;
18 // };
19 // GEOFILTER?: {
20 // field: string;
21 // lon: number;
22 // lat: number;
23 // radius: number;
24 // unit: 'm' | 'km' | 'mi' | 'ft';
25 // };
26 INKEYS?: string | Array<string>;
27 INFIELDS?: string | Array<string>;
28 RETURN?: string | Array<string>;
29 SUMMARIZE?: true | {
30 FIELDS?: PropertyName | Array<PropertyName>;
31 FRAGS?: number;
32 LEN?: number;
33 SEPARATOR?: string;
34 };
35 HIGHLIGHT?: true | {
36 FIELDS?: PropertyName | Array<PropertyName>;
37 TAGS?: {
38 open: string;
39 close: string;
40 };
41 };
42 SLOP?: number;
43 INORDER?: true;
44 LANGUAGE?: RedisSearchLanguages;
45 EXPANDER?: string;
46 SCORER?: string;
47 // EXPLAINSCORE?: true; // TODO: WITHSCORES
48 // PAYLOAD?: ;
49 SORTBY?: SortByProperty;
50 // MSORTBY?: SortByProperty | Array<SortByProperty>;
51 LIMIT?: {
52 from: number | string;
53 size: number | string;
54 };
55 PARAMS?: Params;
56 DIALECT?: number;
57 TIMEOUT?: number;
58 }
59
60 export function transformArguments(
61 index: string,
62 query: string,
63 options?: SearchOptions
64 ): RedisCommandArguments {
65 return pushSearchOptions(
66 ['FT.SEARCH', index, query],
67 options
68 );
69 }
70
71 export type SearchRawReply = Array<any>;
72
73 export function transformReply(reply: SearchRawReply, withoutDocuments: boolean): SearchReply {
74 const documents = [];
75 let i = 1;
76 while (i < reply.length) {
77 documents.push({
78 id: reply[i++],
79 value: withoutDocuments ? Object.create(null) : documentValue(reply[i++])
80 });
81 }
82
83 return {
84 total: reply[0],
85 documents
86 };
87 }
88
89 function documentValue(tuples: any) {
90 const message = Object.create(null);
91
92 let i = 0;
93 while (i < tuples.length) {
94 const key = tuples[i++],
95 value = tuples[i++];
96 if (key === '$') { // might be a JSON reply
97 try {
98 Object.assign(message, JSON.parse(value));
99 continue;
100 } catch {
101 // set as a regular property if not a valid JSON
102 }
103 }
104
105 message[key] = value;
106 }
107
108 return message;
109 }