collections.service.ts 10 KB

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