collections.service.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import { MilvusService } from '../milvus/milvus.service';
  2. import {
  3. CreateCollectionReq,
  4. DescribeCollectionReq,
  5. DropCollectionReq,
  6. GetCollectionStatisticsReq,
  7. GetIndexStateReq,
  8. InsertReq,
  9. LoadCollectionReq,
  10. ReleaseLoadCollectionReq,
  11. SearchReq,
  12. RenameCollectionReq,
  13. AlterAliasReq,
  14. CreateAliasReq,
  15. DropAliasReq,
  16. ShowCollectionsReq,
  17. ShowCollectionsType,
  18. DeleteEntitiesReq,
  19. GetCompactionStateReq,
  20. GetQuerySegmentInfoReq,
  21. GePersistentSegmentInfoReq,
  22. CompactReq,
  23. CountReq,
  24. } from '@zilliz/milvus2-sdk-node';
  25. import { Parser } from '@json2csv/plainjs';
  26. import { throwErrorFromSDK, findKeyValue, genRows, ROW_COUNT } from '../utils';
  27. import { QueryDto, ImportSampleDto, GetReplicasDto } from './dto';
  28. export class CollectionsService {
  29. constructor(private milvusService: MilvusService) {}
  30. async getCollections(data?: ShowCollectionsReq) {
  31. const res = await this.milvusService.client.showCollections(data);
  32. throwErrorFromSDK(res.status);
  33. return res;
  34. }
  35. async createCollection(data: CreateCollectionReq) {
  36. const res = await this.milvusService.client.createCollection(data);
  37. throwErrorFromSDK(res);
  38. return res;
  39. }
  40. async describeCollection(data: DescribeCollectionReq) {
  41. const res = await this.milvusService.client.describeCollection(data);
  42. throwErrorFromSDK(res.status);
  43. return res;
  44. }
  45. async renameCollection(data: RenameCollectionReq) {
  46. const res = await this.milvusService.client.renameCollection(data);
  47. throwErrorFromSDK(res);
  48. return res;
  49. }
  50. async dropCollection(data: DropCollectionReq) {
  51. const res = await this.milvusService.client.dropCollection(data);
  52. throwErrorFromSDK(res);
  53. return res;
  54. }
  55. async loadCollection(data: LoadCollectionReq) {
  56. const res = await this.milvusService.client.loadCollection(data);
  57. throwErrorFromSDK(res);
  58. return res;
  59. }
  60. async releaseCollection(data: ReleaseLoadCollectionReq) {
  61. const res = await this.milvusService.client.releaseCollection(data);
  62. throwErrorFromSDK(res);
  63. return res;
  64. }
  65. async getCollectionStatistics(data: GetCollectionStatisticsReq) {
  66. const res = await this.milvusService.client.getCollectionStatistics(data);
  67. throwErrorFromSDK(res.status);
  68. return res;
  69. }
  70. async count(data: CountReq) {
  71. let count = 0;
  72. try {
  73. const countRes = await this.milvusService.client.count(data);
  74. count = countRes.data;
  75. } catch (error) {
  76. const collectionStatisticsRes = await this.getCollectionStatistics(data);
  77. count = collectionStatisticsRes.data.row_count;
  78. }
  79. return count;
  80. }
  81. async insert(data: InsertReq) {
  82. const res = await this.milvusService.client.insert(data);
  83. throwErrorFromSDK(res.status);
  84. return res;
  85. }
  86. async deleteEntities(data: DeleteEntitiesReq) {
  87. const res = await this.milvusService.client.deleteEntities(data);
  88. throwErrorFromSDK(res.status);
  89. return res;
  90. }
  91. async vectorSearch(data: SearchReq) {
  92. const now = Date.now();
  93. const res = await this.milvusService.client.search(data);
  94. const after = Date.now();
  95. throwErrorFromSDK(res.status);
  96. Object.assign(res, { latency: after - now });
  97. return res;
  98. }
  99. async createAlias(data: CreateAliasReq) {
  100. const res = await this.milvusService.client.createAlias(data);
  101. throwErrorFromSDK(res);
  102. return res;
  103. }
  104. async alterAlias(data: AlterAliasReq) {
  105. const res = await this.milvusService.client.alterAlias(data);
  106. throwErrorFromSDK(res);
  107. return res;
  108. }
  109. async dropAlias(data: DropAliasReq) {
  110. const res = await this.milvusService.client.dropAlias(data);
  111. throwErrorFromSDK(res);
  112. return res;
  113. }
  114. async getReplicas(data: GetReplicasDto) {
  115. const res = await this.milvusService.client.getReplicas(data);
  116. return res;
  117. }
  118. async query(
  119. data: {
  120. collection_name: string;
  121. } & QueryDto
  122. ) {
  123. const now = Date.now();
  124. const res = await this.milvusService.client.query(data);
  125. const after = Date.now();
  126. throwErrorFromSDK(res.status);
  127. Object.assign(res, { latency: after - now });
  128. return res;
  129. }
  130. /**
  131. * We do not throw error for this.
  132. * Because if collection dont have index, it will throw error.
  133. * We need wait for milvus error code.
  134. * @param data
  135. * @returns
  136. */
  137. async getIndexInfo(data: GetIndexStateReq) {
  138. const res = await this.milvusService.client.describeIndex(data);
  139. return res;
  140. }
  141. /**
  142. * Get all collections meta data
  143. * @returns {id:string, collection_name:string, schema:Field[], autoID:boolean, rowCount: string, consistency_level:string}
  144. */
  145. async getAllCollections() {
  146. const data: any = [];
  147. const res = await this.getCollections();
  148. const loadedCollections = await this.getCollections({
  149. type: ShowCollectionsType.Loaded,
  150. });
  151. if (res.data.length > 0) {
  152. for (const item of res.data) {
  153. const { name } = item;
  154. const collectionInfo = await this.describeCollection({
  155. collection_name: name,
  156. });
  157. let count: number | string;
  158. const collectionStatisticsRes = await this.getCollectionStatistics({
  159. collection_name: name,
  160. });
  161. count = collectionStatisticsRes.data.row_count;
  162. // try {
  163. // const countRes = await this.count({
  164. // collection_name: name,
  165. // });
  166. // count = countRes.data;
  167. // } catch (error) {
  168. // }
  169. const indexRes = await this.getIndexInfo({
  170. collection_name: item.name,
  171. });
  172. const autoID = collectionInfo.schema.fields.find(
  173. v => v.is_primary_key === true
  174. )?.autoID;
  175. const loadCollection = loadedCollections.data.find(
  176. v => v.name === name
  177. );
  178. const loadedPercentage = !loadCollection
  179. ? '-1'
  180. : loadCollection.loadedPercentage;
  181. let replicas;
  182. try {
  183. replicas = loadCollection
  184. ? await this.getReplicas({
  185. collectionID: collectionInfo.collectionID,
  186. })
  187. : replicas;
  188. } catch (e) {
  189. console.log('ignore getReplica');
  190. }
  191. data.push({
  192. aliases: collectionInfo.aliases,
  193. collection_name: name,
  194. schema: collectionInfo.schema,
  195. description: collectionInfo.schema.description,
  196. autoID,
  197. rowCount: count,
  198. id: collectionInfo.collectionID,
  199. loadedPercentage,
  200. createdTime: parseInt(collectionInfo.created_utc_timestamp, 10),
  201. index_descriptions: indexRes,
  202. consistency_level: collectionInfo.consistency_level,
  203. replicas: replicas && replicas.replicas,
  204. });
  205. }
  206. }
  207. // add default sort - Descending order
  208. data.sort((a: any, b: any) => b.createdTime - a.createdTime);
  209. return data;
  210. }
  211. async getLoadedCollections() {
  212. const data = [];
  213. const res = await this.getCollections({
  214. type: ShowCollectionsType.Loaded,
  215. });
  216. if (res.data.length > 0) {
  217. for (const item of res.data) {
  218. const { id, name } = item;
  219. const count = this.count({ collection_name: name });
  220. data.push({
  221. id,
  222. collection_name: name,
  223. rowCount: count,
  224. ...item,
  225. });
  226. }
  227. }
  228. return data;
  229. }
  230. /**
  231. * Get collections statistics data
  232. * @returns {collectionCount:number, totalData:number}
  233. */
  234. async getStatistics() {
  235. const data = {
  236. collectionCount: 0,
  237. totalData: 0,
  238. };
  239. const res = await this.getCollections();
  240. data.collectionCount = res.data.length;
  241. if (res.data.length > 0) {
  242. for (const item of res.data) {
  243. const collectionStatistics = await this.getCollectionStatistics({
  244. collection_name: item.name,
  245. });
  246. const rowCount = findKeyValue(collectionStatistics.stats, ROW_COUNT);
  247. data.totalData += isNaN(Number(rowCount)) ? 0 : Number(rowCount);
  248. }
  249. }
  250. return data;
  251. }
  252. /**
  253. * Get all collection index status
  254. * @returns {collection_name:string, index_descriptions: index_descriptions}[]
  255. */
  256. async getCollectionsIndexStatus() {
  257. const data = [];
  258. const res = await this.getCollections();
  259. if (res.data.length > 0) {
  260. for (const item of res.data) {
  261. const indexRes = await this.getIndexInfo({
  262. collection_name: item.name,
  263. });
  264. data.push({
  265. collection_name: item.name,
  266. index_descriptions: indexRes,
  267. });
  268. }
  269. }
  270. return data;
  271. }
  272. /**
  273. * Load sample data into collection
  274. */
  275. async importSample({
  276. collection_name,
  277. size,
  278. download,
  279. format,
  280. }: ImportSampleDto) {
  281. const collectionInfo = await this.describeCollection({ collection_name });
  282. const fields_data = genRows(
  283. collectionInfo.schema.fields,
  284. parseInt(size, 10),
  285. collectionInfo.schema.enable_dynamic_field
  286. );
  287. if (download) {
  288. const parser = new Parser({});
  289. const sampleFile =
  290. format === 'csv'
  291. ? parser.parse(fields_data)
  292. : JSON.stringify(fields_data);
  293. // If download is true, return the generated data directly
  294. return { sampleFile };
  295. } else {
  296. // Otherwise, insert the data into the collection
  297. return await this.insert({ collection_name, fields_data });
  298. }
  299. }
  300. async getCompactionState(data: GetCompactionStateReq) {
  301. const res = await this.milvusService.client.getCompactionState(data);
  302. throwErrorFromSDK(res.status);
  303. return res;
  304. }
  305. async getQuerySegmentInfo(data: GetQuerySegmentInfoReq) {
  306. const res = await this.milvusService.client.getQuerySegmentInfo(data);
  307. throwErrorFromSDK(res.status);
  308. return res;
  309. }
  310. async getPersistentSegmentInfo(data: GePersistentSegmentInfoReq) {
  311. const res = await this.milvusService.client.getPersistentSegmentInfo(data);
  312. throwErrorFromSDK(res.status);
  313. return res;
  314. }
  315. async compact(data: CompactReq) {
  316. const res = await this.milvusService.client.compact(data);
  317. throwErrorFromSDK(res.status);
  318. return res;
  319. }
  320. }