1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684 |
- /*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
- package io.milvus.client;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.google.common.util.concurrent.ListenableFuture;
- import io.milvus.grpc.*;
- import io.milvus.param.*;
- import io.milvus.param.collection.*;
- //import io.milvus.param.credential.*;
- import io.milvus.param.highlevel.dml.DeleteIdsParam;
- import io.milvus.param.highlevel.dml.GetIdsParam;
- import io.milvus.param.highlevel.dml.response.DeleteResponse;
- import io.milvus.param.highlevel.dml.response.GetResponse;
- import io.milvus.param.dml.InsertParam;
- import io.milvus.param.dml.QueryParam;
- import io.milvus.param.dml.SearchParam;
- import io.milvus.param.index.CreateIndexParam;
- import io.milvus.param.index.DescribeIndexParam;
- import io.milvus.param.index.DropIndexParam;
- import io.milvus.param.index.GetIndexStateParam;
- import io.milvus.param.partition.GetPartitionStatisticsParam;
- import io.milvus.param.partition.ShowPartitionsParam;
- import io.milvus.response.*;
- import org.apache.commons.text.RandomStringGenerator;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.codehaus.plexus.util.FileUtils;
- import org.junit.jupiter.api.Assertions;
- import org.junit.jupiter.api.BeforeAll;
- import org.junit.jupiter.api.AfterAll;
- import org.junit.jupiter.api.Test;
- import java.nio.ByteBuffer;
- import java.util.*;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.TimeUnit;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertTrue;
- class MilvusClientDockerTest {
- private static final Logger logger = LogManager.getLogger("MilvusClientTest");
- private static MilvusClient client;
- private static RandomStringGenerator generator;
- private static final int dimension = 128;
- private static final Boolean useDockerCompose = Boolean.TRUE;
- private static void startDockerContainer() {
- if (!useDockerCompose) {
- return;
- }
- // start the test container
- Runtime runtime = Runtime.getRuntime();
- String bashCommand = "docker-compose up -d";
- try {
- logger.info(bashCommand);
- Process pro = runtime.exec(bashCommand);
- int status = pro.waitFor();
- if (status != 0) {
- logger.error("Failed to start docker compose, status " + status);
- }
- logger.info("Docker compose is up");
- } catch (Throwable t) {
- logger.error("Failed to execute docker compose up", t);
- }
- ConnectParam connectParam = connectParamBuilder().withAuthorization("root", "Milvus").build();
- MilvusServiceClient tempClient = new MilvusServiceClient(connectParam);
- long waitTime = 0;
- while (true) {
- // although milvus container is alive, it is still in initializing,
- // connection will failed and get error "proxy not health".
- // check health state for every few seconds, until the server is ready.
- long checkInterval = 3;
- try {
- TimeUnit.SECONDS.sleep(checkInterval);
- } catch (InterruptedException t) {
- logger.error("Interrupted", t);
- break;
- }
- try{
- R<CheckHealthResponse> resp = tempClient.checkHealth();
- if (resp.getData().getIsHealthy()) {
- logger.info(String.format("Milvus service is ready after %d seconds", waitTime));
- break;
- }
- logger.info("Milvus service is not ready, waiting...");
- } catch (Throwable t) {
- logger.error("Milvus service is in initialize, not able to connect", t);
- }
- waitTime += checkInterval;
- if (waitTime > 120) {
- logger.error(String.format("Milvus service failed to start within %d seconds", waitTime));
- break;
- }
- }
- }
- private static void stopDockerContainer() {
- if (!useDockerCompose) {
- return;
- }
- // stop all test dockers
- Runtime runtime = Runtime.getRuntime();
- String bashCommand = "docker-compose down";
- try {
- logger.info("Milvus service stopping...");
- TimeUnit.SECONDS.sleep(5);
- logger.info(bashCommand);
- Process pro = runtime.exec(bashCommand);
- int status = pro.waitFor();
- if (status != 0) {
- logger.error("Failed to stop test docker containers" + pro.getOutputStream().toString());
- }
- } catch (Throwable t) {
- logger.error("Failed to execute docker compose down", t);
- }
- // clean up log dir
- runtime = Runtime.getRuntime();
- bashCommand = "docker-compose rm";
- try {
- logger.info(bashCommand);
- Process pro = runtime.exec(bashCommand);
- int status = pro.waitFor();
- if (status != 0) {
- logger.error("Failed to clean up test docker containers" + pro.getOutputStream().toString());
- }
- logger.error("Clean up volume directory of Docker");
- FileUtils.cleanDirectory("volumes");
- } catch (Throwable t) {
- logger.error("Failed to remove docker compose volume", t);
- }
- }
- @BeforeAll
- public static void setUp() {
- startDockerContainer();
- ConnectParam connectParam = connectParamBuilder().withAuthorization("root", "Milvus").build();
- client = new MilvusServiceClient(connectParam);
- generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
- }
- @AfterAll
- public static void tearDown() {
- if (client != null) {
- client.close();
- }
- stopDockerContainer();
- }
- protected static ConnectParam.Builder connectParamBuilder() {
- return connectParamBuilder("localhost", 19530);
- }
- private static ConnectParam.Builder connectParamBuilder(String host, int port) {
- return ConnectParam.newBuilder().withHost(host).withPort(port);
- }
- private List<List<Float>> generateFloatVectors(int count) {
- Random ran = new Random();
- List<List<Float>> vectors = new ArrayList<>();
- for (int n = 0; n < count; ++n) {
- List<Float> vector = new ArrayList<>();
- for (int i = 0; i < dimension; ++i) {
- vector.add(ran.nextFloat());
- }
- vectors.add(vector);
- }
- return vectors;
- }
- private List<List<Float>> normalizeFloatVectors(List<List<Float>> src) {
- for (List<Float> vector : src) {
- double total = 0.0;
- for (Float val : vector) {
- total = total + val * val;
- }
- float squre = (float) Math.sqrt(total);
- for (int i = 0; i < vector.size(); ++i) {
- vector.set(i, vector.get(i) / squre);
- }
- }
- return src;
- }
- private List<ByteBuffer> generateBinaryVectors(int count) {
- Random ran = new Random();
- List<ByteBuffer> vectors = new ArrayList<>();
- int byteCount = dimension / 8;
- for (int n = 0; n < count; ++n) {
- ByteBuffer vector = ByteBuffer.allocate(byteCount);
- for (int i = 0; i < byteCount; ++i) {
- vector.put((byte) ran.nextInt(Byte.MAX_VALUE));
- }
- vectors.add(vector);
- }
- return vectors;
- }
- @Test
- void testFloatVectors() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "long_field";
- String field2Name = "vec_field";
- String field3Name = "bool_field";
- String field4Name = "double_field";
- String field5Name = "int_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .withDescription("identity")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDescription("face")
- .withDimension(dimension)
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.Bool)
- .withName(field3Name)
- .withDescription("gender")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.Double)
- .withName(field4Name)
- .withDescription("weight")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.Int8)
- .withName(field5Name)
- .withDescription("age")
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .withFieldTypes(fieldsSchema)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- R<DescribeCollectionResponse> response = client.describeCollection(DescribeCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- DescCollResponseWrapper desc = new DescCollResponseWrapper(response.getData());
- System.out.println(desc.toString());
- R<ShowPartitionsResponse> spResp = client.showPartitions(ShowPartitionsParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- System.out.println(spResp);
- ShowPartResponseWrapper wra = new ShowPartResponseWrapper(spResp.getData());
- List<ShowPartResponseWrapper.PartitionInfo> parts = wra.getPartitionsInfo();
- System.out.println("Partition num: "+parts.size());
- // insert data
- int rowCount = 10000;
- List<Long> ids = new ArrayList<>();
- List<Boolean> genders = new ArrayList<>();
- List<Double> weights = new ArrayList<>();
- List<Short> ages = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- ids.add(i);
- genders.add(i % 3 == 0 ? Boolean.TRUE : Boolean.FALSE);
- weights.add(((double) (i + 1) / 100));
- ages.add((short) ((i + 1) % 99));
- }
- List<List<Float>> vectors = generateFloatVectors(rowCount);
- List<InsertParam.Field> fieldsInsert = new ArrayList<>();
- fieldsInsert.add(new InsertParam.Field(field1Name, ids));
- fieldsInsert.add(new InsertParam.Field(field5Name, ages));
- fieldsInsert.add(new InsertParam.Field(field4Name, weights));
- fieldsInsert.add(new InsertParam.Field(field3Name, genders));
- fieldsInsert.add(new InsertParam.Field(field2Name, vectors));
- InsertParam insertParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFields(fieldsInsert)
- .build();
- R<MutationResult> insertR = client.withTimeout(10, TimeUnit.SECONDS).insert(insertParam);
- assertEquals(R.Status.Success.getCode(), insertR.getStatus().intValue());
- MutationResultWrapper insertResultWrapper = new MutationResultWrapper(insertR.getData());
- System.out.println(insertResultWrapper.getInsertCount() + " rows inserted");
- // get collection statistics
- R<GetCollectionStatisticsResponse> statR = client.getCollectionStatistics(GetCollectionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statR.getStatus().intValue());
- GetCollStatResponseWrapper stat = new GetCollStatResponseWrapper(statR.getData());
- System.out.println("Collection row count: " + stat.getRowCount());
- // get partition statistics
- R<GetPartitionStatisticsResponse> statPartR = client.getPartitionStatistics(GetPartitionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withPartitionName("_default") // each collection has '_default' partition
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statPartR.getStatus().intValue());
- GetPartStatResponseWrapper statPart = new GetPartStatResponseWrapper(statPartR.getData());
- System.out.println("Partition row count: " + statPart.getRowCount());
- // create index on scalar field
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field5Name)
- .withIndexType(IndexType.STL_SORT)
- .withSyncMode(Boolean.TRUE)
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // create index on vector field
- indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexName("abv")
- .withIndexType(IndexType.HNSW)
- .withMetricType(MetricType.L2)
- .withExtraParam("{\"M\":16,\"efConstruction\":64}")
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // get index description
- DescribeIndexParam descIndexParam = DescribeIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build();
- R<DescribeIndexResponse> descIndexR = client.describeIndex(descIndexParam);
- assertEquals(R.Status.Success.getCode(), descIndexR.getStatus().intValue());
- DescIndexResponseWrapper indexDesc = new DescIndexResponseWrapper(descIndexR.getData());
- System.out.println("Index description: " + indexDesc.toString());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- // show collections
- R<ShowCollectionsResponse> showR = client.showCollections(ShowCollectionsParam.newBuilder()
- .addCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), showR.getStatus().intValue());
- ShowCollResponseWrapper info = new ShowCollResponseWrapper(showR.getData());
- System.out.println("Collection info: " + info.toString());
- // show partitions
- R<ShowPartitionsResponse> showPartR = client.showPartitions(ShowPartitionsParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .addPartitionName("_default") // each collection has a '_default' partition
- .build());
- assertEquals(R.Status.Success.getCode(), showPartR.getStatus().intValue());
- ShowPartResponseWrapper infoPart = new ShowPartResponseWrapper(showPartR.getData());
- System.out.println("Partition info: " + infoPart.toString());
- // query vectors to verify
- List<Long> queryIDs = new ArrayList<>();
- List<Double> compareWeights = new ArrayList<>();
- int nq = 5;
- Random ran = new Random();
- int randomIndex = ran.nextInt(rowCount - nq);
- for (int i = randomIndex; i < randomIndex + nq; ++i) {
- queryIDs.add(ids.get(i));
- compareWeights.add(weights.get(i));
- }
- String expr = field1Name + " in " + queryIDs.toString();
- List<String> outputFields = Arrays.asList(field1Name, field2Name, field3Name, field4Name, field5Name);
- QueryParam queryParam = QueryParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withExpr(expr)
- .withOutFields(outputFields)
- .build();
- R<QueryResults> queryR = client.query(queryParam);
- assertEquals(R.Status.Success.getCode(), queryR.getStatus().intValue());
- // verify query result
- QueryResultsWrapper queryResultsWrapper = new QueryResultsWrapper(queryR.getData());
- for (String fieldName : outputFields) {
- FieldDataWrapper wrapper = queryResultsWrapper.getFieldWrapper(fieldName);
- System.out.println("Query data of " + fieldName + ", row count: " + wrapper.getRowCount());
- System.out.println(wrapper.getFieldData());
- assertEquals(nq, wrapper.getFieldData().size());
- if (fieldName.compareTo(field1Name) == 0) {
- List<?> out = queryResultsWrapper.getFieldWrapper(field1Name).getFieldData();
- assertEquals(nq, out.size());
- for (Object o : out) {
- long id = (Long) o;
- assertTrue(queryIDs.contains(id));
- }
- }
- }
- // Note: the query() return vectors are not in same sequence to the input
- // here we cannot compare vector one by one
- // the boolean also cannot be compared
- if (outputFields.contains(field2Name)) {
- assertTrue(queryResultsWrapper.getFieldWrapper(field2Name).isVectorField());
- List<?> out = queryResultsWrapper.getFieldWrapper(field2Name).getFieldData();
- assertEquals(nq, out.size());
- }
- if (outputFields.contains(field3Name)) {
- List<?> out = queryResultsWrapper.getFieldWrapper(field3Name).getFieldData();
- assertEquals(nq, out.size());
- }
- if (outputFields.contains(field4Name)) {
- List<?> out = queryResultsWrapper.getFieldWrapper(field4Name).getFieldData();
- assertEquals(nq, out.size());
- for (Object o : out) {
- double d = (Double) o;
- assertTrue(compareWeights.contains(d));
- }
- }
- // query with offset and limit
- int queryLimit = 5;
- expr = field5Name + " > 1"; // "age > 1"
- queryParam = QueryParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withExpr(expr)
- .withOffset(100L)
- .withLimit((long) queryLimit)
- .build();
- queryR = client.query(queryParam);
- assertEquals(R.Status.Success.getCode(), queryR.getStatus().intValue());
- queryResultsWrapper = new QueryResultsWrapper(queryR.getData());
- // we didn't set the output fields, only primary key field is returned
- List<?> out = queryResultsWrapper.getFieldWrapper(field1Name).getFieldData();
- assertEquals(queryLimit, out.size());
- // pick some vectors to search
- List<Long> targetVectorIDs = new ArrayList<>();
- List<List<Float>> targetVectors = new ArrayList<>();
- for (int i = randomIndex; i < randomIndex + nq; ++i) {
- targetVectorIDs.add(ids.get(i));
- targetVectors.add(vectors.get(i));
- }
- int topK = 5;
- SearchParam searchParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.L2)
- .withTopK(topK)
- .withVectors(targetVectors)
- .withVectorFieldName(field2Name)
- .withParams("{\"ef\":64}")
- .addOutField(field4Name)
- .build();
- R<SearchResults> searchR = client.search(searchParam);
- // System.out.println(searchR);
- assertEquals(R.Status.Success.getCode(), searchR.getStatus().intValue());
- // verify the search result
- SearchResultsWrapper results = new SearchResultsWrapper(searchR.getData().getResults());
- for (int i = 0; i < targetVectors.size(); ++i) {
- List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
- System.out.println("The result of No." + i + " target vector(ID = " + targetVectorIDs.get(i) + "):");
- System.out.println(scores);
- assertEquals(targetVectorIDs.get(i).longValue(), scores.get(0).getLongID());
- }
- List<?> fieldData = results.getFieldData(field4Name, 0);
- assertEquals(topK, fieldData.size());
- fieldData = results.getFieldData(field4Name, nq - 1);
- assertEquals(topK, fieldData.size());
- // release collection
- ReleaseCollectionParam releaseCollectionParam = ReleaseCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName).build();
- R<RpcStatus> releaseCollectionR = client.releaseCollection(releaseCollectionParam);
- assertEquals(R.Status.Success.getCode(), releaseCollectionR.getStatus().intValue());
- // drop index
- DropIndexParam dropIndexParam = DropIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build();
- R<RpcStatus> dropIndexR = client.dropIndex(dropIndexParam);
- assertEquals(R.Status.Success.getCode(), dropIndexR.getStatus().intValue());
- // drop collection
- DropCollectionParam dropParam = DropCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build();
- R<RpcStatus> dropR = client.dropCollection(dropParam);
- assertEquals(R.Status.Success.getCode(), dropR.getStatus().intValue());
- }
- @Test
- void testBinaryVectors() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "field1";
- String field2Name = "field2";
- FieldType field1 = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(true)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .withDescription("hello")
- .build();
- FieldType field2 = FieldType.newBuilder()
- .withDataType(DataType.BinaryVector)
- .withName(field2Name)
- .withDescription("world")
- .withDimension(dimension)
- .build();
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .addFieldType(field1)
- .addFieldType(field2)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- // insert data
- int rowCount = 10000;
- List<ByteBuffer> vectors = generateBinaryVectors(rowCount);
- List<InsertParam.Field> fields = new ArrayList<>();
- // no need to provide id here since this field is auto_id
- fields.add(new InsertParam.Field(field2Name, vectors));
- InsertParam insertParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFields(fields)
- .build();
- R<MutationResult> insertR = client.insert(insertParam);
- assertEquals(R.Status.Success.getCode(), insertR.getStatus().intValue());
- // System.out.println(insertR.getData());
- MutationResultWrapper insertResultWrapper = new MutationResultWrapper(insertR.getData());
- System.out.println(insertResultWrapper.getInsertCount() + " rows inserted");
- List<Long> ids = insertResultWrapper.getLongIDs();
- // System.out.println("Auto-generated ids: " + ids);
- // get collection statistics
- R<GetCollectionStatisticsResponse> statR = client.getCollectionStatistics(GetCollectionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statR.getStatus().intValue());
- GetCollStatResponseWrapper stat = new GetCollStatResponseWrapper(statR.getData());
- System.out.println("Collection row count: " + stat.getRowCount());
- // create index
- CreateIndexParam indexParam2 = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexType(IndexType.BIN_IVF_FLAT)
- .withExtraParam("{\"nlist\":64}")
- .withMetricType(MetricType.JACCARD)
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- R<RpcStatus> createIndexR2 = client.createIndex(indexParam2);
- assertEquals(R.Status.Success.getCode(), createIndexR2.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- // search with BIN_FLAT index
- int searchTarget = 99;
- List<ByteBuffer> oneVector = new ArrayList<>();
- oneVector.add(vectors.get(searchTarget));
- SearchParam searchOneParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.JACCARD)
- .withTopK(5)
- .withVectors(oneVector)
- .withVectorFieldName(field2Name)
- .addOutField(field2Name)
- .build();
- R<SearchResults> searchOne = client.search(searchOneParam);
- assertEquals(R.Status.Success.getCode(), searchOne.getStatus().intValue());
- SearchResultsWrapper oneResult = new SearchResultsWrapper(searchOne.getData().getResults());
- List<SearchResultsWrapper.IDScore> oneScores = oneResult.getIDScore(0);
- System.out.println("The search result of id " + ids.get(searchTarget) + " with SUPERSTRUCTURE metric:");
- System.out.println(oneScores);
- // verify the output vector, the top1 item is equal to the target vector
- List<?> items = oneResult.getFieldData(field2Name, 0);
- Assertions.assertEquals(items.size(), 5);
- ByteBuffer firstItem = (ByteBuffer) items.get(0);
- for (int i = 0; i < firstItem.limit(); ++i) {
- Assertions.assertEquals(firstItem.get(i), vectors.get(searchTarget).get(i));
- }
- // release collection
- ReleaseCollectionParam releaseCollectionParam = ReleaseCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName).build();
- R<RpcStatus> releaseCollectionR = client.releaseCollection(releaseCollectionParam);
- assertEquals(R.Status.Success.getCode(), releaseCollectionR.getStatus().intValue());
- DropIndexParam dropIndexParam = DropIndexParam.newBuilder()
- .withCollectionName(randomCollectionName).build();
- R<RpcStatus> dropIndexR = client.dropIndex(dropIndexParam);
- assertEquals(R.Status.Success.getCode(), dropIndexR.getStatus().intValue());
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexName("abv")
- .withIndexType(IndexType.BIN_IVF_FLAT)
- .withMetricType(MetricType.HAMMING)
- .withExtraParam("{\"nlist\":64}")
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // get index description
- DescribeIndexParam descIndexParam = DescribeIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build();
- R<DescribeIndexResponse> descIndexR = client.describeIndex(descIndexParam);
- assertEquals(R.Status.Success.getCode(), descIndexR.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR2 = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR2.getStatus().intValue());
- // pick some vectors to search with index
- int nq = 5;
- List<Long> targetVectorIDs = new ArrayList<>();
- List<ByteBuffer> targetVectors = new ArrayList<>();
- Random ran = new Random();
- int randomIndex = ran.nextInt(rowCount - nq);
- for (int i = randomIndex; i < randomIndex + nq; ++i) {
- targetVectorIDs.add(ids.get(i));
- targetVectors.add(vectors.get(i));
- }
- int topK = 5;
- SearchParam searchParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.HAMMING)
- .withTopK(topK)
- .withVectors(targetVectors)
- .withVectorFieldName(field2Name)
- .withParams("{\"nprobe\":8}")
- .build();
- R<SearchResults> searchR = client.search(searchParam);
- // System.out.println(searchR);
- assertEquals(R.Status.Success.getCode(), searchR.getStatus().intValue());
- // verify the search result
- SearchResultsWrapper results = new SearchResultsWrapper(searchR.getData().getResults());
- for (int i = 0; i < targetVectors.size(); ++i) {
- List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
- System.out.println("The result of No." + i + " target vector(ID = " + targetVectorIDs.get(i) + "):");
- System.out.println(scores);
- assertEquals(targetVectorIDs.get(i).longValue(), scores.get(0).getLongID());
- }
- // drop collection
- DropCollectionParam dropParam = DropCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build();
- R<RpcStatus> dropR = client.dropCollection(dropParam);
- assertEquals(R.Status.Success.getCode(), dropR.getStatus().intValue());
- }
- @Test
- void testAsyncMethods() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "long_field";
- String field2Name = "vec_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(true)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .withDescription("identity")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDescription("face")
- .withDimension(dimension)
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .withFieldTypes(fieldsSchema)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- // insert async
- List<ListenableFuture<R<MutationResult>>> futureResponses = new ArrayList<>();
- int rowCount = 1000;
- for (long i = 0L; i < 10; ++i) {
- List<List<Float>> vectors = normalizeFloatVectors(generateFloatVectors(rowCount));
- List<InsertParam.Field> fieldsInsert = new ArrayList<>();
- fieldsInsert.add(new InsertParam.Field(field2Name, vectors));
- InsertParam insertParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFields(fieldsInsert)
- .build();
- ListenableFuture<R<MutationResult>> insertFuture = client.insertAsync(insertParam);
- futureResponses.add(insertFuture);
- }
- // get insert result
- List<Long> queryIDs = new ArrayList<>();
- for (ListenableFuture<R<MutationResult>> response : futureResponses) {
- try {
- R<MutationResult> insertR = response.get();
- assertEquals(R.Status.Success.getCode(), insertR.getStatus().intValue());
- MutationResultWrapper wrapper = new MutationResultWrapper(insertR.getData());
- queryIDs.add(wrapper.getLongIDs().get(0));
- } catch (ExecutionException | InterruptedException e) {
- System.out.println("failed to insert:" + e.getMessage());
- return;
- }
- }
- // get collection statistics
- R<GetCollectionStatisticsResponse> statR = client.getCollectionStatistics(GetCollectionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statR.getStatus().intValue());
- GetCollStatResponseWrapper stat = new GetCollStatResponseWrapper(statR.getData());
- System.out.println("Collection row count: " + stat.getRowCount());
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexType(IndexType.FLAT)
- .withMetricType(MetricType.IP)
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- // search async
- List<List<Float>> targetVectors = normalizeFloatVectors(generateFloatVectors(2));
- int topK = 5;
- SearchParam searchParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.IP)
- .withTopK(topK)
- .withVectors(targetVectors)
- .withVectorFieldName(field2Name)
- .build();
- ListenableFuture<R<SearchResults>> searchFuture = client.searchAsync(searchParam);
- // query async
- String expr = field1Name + " in " + queryIDs.toString();
- List<String> outputFields = Arrays.asList(field1Name, field2Name);
- QueryParam queryParam = QueryParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withExpr(expr)
- .withOutFields(outputFields)
- .build();
- ListenableFuture<R<QueryResults>> queryFuture = client.queryAsync(queryParam);
- try {
- // get search results
- R<SearchResults> searchR = searchFuture.get();
- assertEquals(R.Status.Success.getCode(), searchR.getStatus().intValue());
- // verify search result
- SearchResultsWrapper results = new SearchResultsWrapper(searchR.getData().getResults());
- System.out.println("Search results:");
- for (int i = 0; i < targetVectors.size(); ++i) {
- List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
- assertEquals(topK, scores.size());
- System.out.println(scores.toString());
- }
- // get query results
- R<QueryResults> queryR = queryFuture.get();
- assertEquals(R.Status.Success.getCode(), queryR.getStatus().intValue());
- // verify query result
- QueryResultsWrapper queryResultsWrapper = new QueryResultsWrapper(queryR.getData());
- for (String fieldName : outputFields) {
- FieldDataWrapper wrapper = queryResultsWrapper.getFieldWrapper(fieldName);
- System.out.println("Query data of " + fieldName + ", row count: " + wrapper.getRowCount());
- System.out.println(wrapper.getFieldData());
- assertEquals(queryIDs.size(), wrapper.getFieldData().size());
- }
- } catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
- }
- // drop collection
- DropCollectionParam dropParam = DropCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build();
- R<RpcStatus> dropR = client.dropCollection(dropParam);
- assertEquals(R.Status.Success.getCode(), dropR.getStatus().intValue());
- }
- // this case can be executed when the milvus image of version 2.1 is published.
- @Test
- void testCredential() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "long_field";
- String field2Name = "vec_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .withDescription("identity")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDescription("face")
- .withDimension(dimension)
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .withFieldTypes(fieldsSchema)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexType(IndexType.IVF_FLAT)
- .withIndexName("xxx")
- .withMetricType(MetricType.L2)
- .withExtraParam("{\"nlist\":256}")
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- client.getIndexState(GetIndexStateParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build());
- R<RpcStatus> dropIndexR = client.dropIndex(DropIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build());
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- @Test
- void testStringField() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "str_id";
- String field2Name = "vec_field";
- String field3Name = "str_field";
- String field4Name = "int_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.VarChar)
- .withName(field1Name)
- .withMaxLength(32)
- .withDescription("string identity")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDescription("face")
- .withDimension(dimension)
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.VarChar)
- .withName(field3Name)
- .withMaxLength(32)
- .withDescription("comment")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.Int64)
- .withName(field4Name)
- .withDescription("sequence")
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .withFieldTypes(fieldsSchema)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- R<DescribeCollectionResponse> response = client.describeCollection(DescribeCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- DescCollResponseWrapper desc = new DescCollResponseWrapper(response.getData());
- System.out.println(desc.toString());
- // insert data
- int rowCount = 10000;
- List<String> ids = new ArrayList<>();
- List<String> comments = new ArrayList<>();
- List<Long> sequences = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- ids.add(generator.generate(8));
- comments.add(generator.generate(8));
- sequences.add(i);
- }
- List<List<Float>> vectors = generateFloatVectors(rowCount);
- List<InsertParam.Field> fieldsInsert = new ArrayList<>();
- fieldsInsert.add(new InsertParam.Field(field1Name, ids));
- fieldsInsert.add(new InsertParam.Field(field3Name, comments));
- fieldsInsert.add(new InsertParam.Field(field2Name, vectors));
- fieldsInsert.add(new InsertParam.Field(field4Name, sequences));
- InsertParam insertParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFields(fieldsInsert)
- .build();
- R<MutationResult> insertR = client.withTimeout(10, TimeUnit.SECONDS).insert(insertParam);
- assertEquals(R.Status.Success.getCode(), insertR.getStatus().intValue());
- MutationResultWrapper insertResultWrapper = new MutationResultWrapper(insertR.getData());
- System.out.println(insertResultWrapper.getInsertCount() + " rows inserted");
- // get collection statistics
- R<GetCollectionStatisticsResponse> statR = client.getCollectionStatistics(GetCollectionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statR.getStatus().intValue());
- GetCollStatResponseWrapper stat = new GetCollStatResponseWrapper(statR.getData());
- System.out.println("Collection row count: " + stat.getRowCount());
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field3Name)
- .withIndexName("stridx")
- .withIndexType(IndexType.TRIE)
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // get index description
- DescribeIndexParam descIndexParam = DescribeIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withIndexName(indexParam.getIndexName())
- .build();
- R<DescribeIndexResponse> descIndexR = client.describeIndex(descIndexParam);
- assertEquals(R.Status.Success.getCode(), descIndexR.getStatus().intValue());
- // create index
- CreateIndexParam indexParam2 = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexType(IndexType.FLAT)
- .withMetricType(MetricType.IP)
- .withSyncMode(Boolean.TRUE)
- .withSyncWaitingInterval(500L)
- .withSyncWaitingTimeout(30L)
- .build();
- R<RpcStatus> createIndexR2 = client.createIndex(indexParam2);
- assertEquals(R.Status.Success.getCode(), createIndexR2.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- // query vectors to verify
- List<Long> queryItems = new ArrayList<>();
- List<String> queryIds = new ArrayList<>();
- int nq = 5;
- Random ran = new Random();
- int randomIndex = ran.nextInt(rowCount - nq);
- for (int i = randomIndex; i < randomIndex + nq; ++i) {
- queryIds.add(ids.get(i));
- queryItems.add(sequences.get(i));
- }
- String expr = field4Name + " in " + queryItems.toString();
- List<String> outputFields = Arrays.asList(field1Name, field3Name);
- QueryParam queryParam = QueryParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withExpr(expr)
- .withOutFields(outputFields)
- .build();
- R<QueryResults> queryR = client.query(queryParam);
- assertEquals(R.Status.Success.getCode(), queryR.getStatus().intValue());
- // verify query result
- QueryResultsWrapper queryResultsWrapper = new QueryResultsWrapper(queryR.getData());
- for (String fieldName : outputFields) {
- FieldDataWrapper wrapper = queryResultsWrapper.getFieldWrapper(fieldName);
- System.out.println("Query data of " + fieldName + ", row count: " + wrapper.getRowCount());
- System.out.println(wrapper.getFieldData());
- assertEquals(nq, wrapper.getFieldData().size());
- if (fieldName.compareTo(field1Name) == 0) {
- List<?> out = queryResultsWrapper.getFieldWrapper(field1Name).getFieldData();
- assertEquals(nq, out.size());
- for (Object o : out) {
- String id = (String) o;
- assertTrue(queryIds.contains(id));
- }
- }
- }
- // search
- int topK = 5;
- List<List<Float>> targetVectors = new ArrayList<>();
- for (Long seq : queryItems) {
- targetVectors.add(vectors.get(seq.intValue()));
- }
- SearchParam searchParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.IP)
- .withTopK(topK)
- .withVectors(targetVectors)
- .withVectorFieldName(field2Name)
- .addOutField(field4Name)
- .build();
- R<SearchResults> searchR = client.search(searchParam);
- assertEquals(R.Status.Success.getCode(), searchR.getStatus().intValue());
- // verify the search result
- SearchResultsWrapper results = new SearchResultsWrapper(searchR.getData().getResults());
- for (int i = 0; i < targetVectors.size(); ++i) {
- List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
- System.out.println("The result of No." + i + " target vector(ID = " + queryIds.get(i) + "):");
- System.out.println(scores);
- }
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- private static void testIndex(String collectionName, String fieldName,
- IndexType type, MetricType metric,
- String params, Boolean syncMode) {
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(collectionName)
- .withFieldName(fieldName)
- .withIndexName("index")
- .withIndexType(type)
- .withMetricType(metric)
- .withExtraParam(params)
- .withSyncMode(syncMode)
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // drop index
- DropIndexParam dropIndexParam = DropIndexParam.newBuilder()
- .withCollectionName(collectionName)
- .withIndexName(indexParam.getIndexName())
- .build();
- R<RpcStatus> dropIndexR = client.dropIndex(dropIndexParam);
- assertEquals(R.Status.Success.getCode(), dropIndexR.getStatus().intValue());
- }
- @Test
- void testFloatVectorIndex() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "idg_field";
- String field2Name = "vec_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDimension(dimension)
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .withFieldTypes(fieldsSchema)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- // test all supported indexes
- Map<IndexType, String> indexTypes = new HashMap<>();
- indexTypes.put(IndexType.FLAT, "{}");
- indexTypes.put(IndexType.IVF_FLAT, "{\"nlist\":128}");
- indexTypes.put(IndexType.IVF_SQ8, "{\"nlist\":128}");
- indexTypes.put(IndexType.IVF_PQ, "{\"nlist\":128, \"m\":16, \"nbits\":8}");
- indexTypes.put(IndexType.ANNOY, "{\"n_trees\":16}");
- indexTypes.put(IndexType.HNSW, "{\"M\":16,\"efConstruction\":64}");
- indexTypes.put(IndexType.RHNSW_FLAT, "{\"M\":16,\"efConstruction\":64}");
- indexTypes.put(IndexType.RHNSW_PQ, "{\"M\":16,\"efConstruction\":64, \"PQM\":16}");
- indexTypes.put(IndexType.RHNSW_SQ, "{\"M\":16,\"efConstruction\":64}");
- List<MetricType> metricTypes = new ArrayList<>();
- metricTypes.add(MetricType.L2);
- metricTypes.add(MetricType.IP);
- for (IndexType type : indexTypes.keySet()) {
- for (MetricType metric : metricTypes) {
- testIndex(randomCollectionName, field2Name, type, metric, indexTypes.get(type), Boolean.TRUE);
- testIndex(randomCollectionName, field2Name, type, metric, indexTypes.get(type), Boolean.FALSE);
- }
- }
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- @Test
- void testBinaryVectorIndex() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "id_field";
- String field2Name = "vector_field";
- FieldType field1 = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(true)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .build();
- FieldType field2 = FieldType.newBuilder()
- .withDataType(DataType.BinaryVector)
- .withName(field2Name)
- .withDimension(dimension)
- .build();
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .addFieldType(field1)
- .addFieldType(field2)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- // test all supported indexes
- List<MetricType> flatMetricTypes = new ArrayList<>();
- flatMetricTypes.add(MetricType.SUBSTRUCTURE);
- flatMetricTypes.add(MetricType.SUPERSTRUCTURE);
- for (MetricType metric : flatMetricTypes) {
- testIndex(randomCollectionName, field2Name, IndexType.BIN_FLAT, metric, "{}", Boolean.TRUE);
- testIndex(randomCollectionName, field2Name, IndexType.BIN_FLAT, metric, "{}", Boolean.FALSE);
- }
- List<MetricType> ivfMetricTypes = new ArrayList<>();
- ivfMetricTypes.add(MetricType.HAMMING);
- ivfMetricTypes.add(MetricType.JACCARD);
- ivfMetricTypes.add(MetricType.TANIMOTO);
- for (MetricType metric : ivfMetricTypes) {
- testIndex(randomCollectionName, field2Name, IndexType.BIN_IVF_FLAT, metric, "{\"nlist\":128}", Boolean.TRUE);
- testIndex(randomCollectionName, field2Name, IndexType.BIN_IVF_FLAT, metric, "{\"nlist\":128}", Boolean.FALSE);
- }
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- @Test
- void testDynamicField() {
- String randomCollectionName = generator.generate(10);
- // collection schema
- String field1Name = "id_field";
- String field2Name = "vec_field";
- String field3Name = "json_field";
- List<FieldType> fieldsSchema = new ArrayList<>();
- fieldsSchema.add(FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .withDescription("identity")
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDescription("face")
- .withDimension(dimension)
- .build());
- fieldsSchema.add(FieldType.newBuilder()
- .withDataType(DataType.JSON)
- .withName(field3Name)
- .withDescription("info")
- .build());
- // create collection
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldTypes(fieldsSchema)
- .withEnableDynamicField(true)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- R<DescribeCollectionResponse> response = client.describeCollection(DescribeCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- DescCollResponseWrapper desc = new DescCollResponseWrapper(response.getData());
- System.out.println(desc.toString());
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(field2Name)
- .withIndexName("abv")
- .withIndexType(IndexType.FLAT)
- .withMetricType(MetricType.L2)
- .withExtraParam("{}")
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- int rowCount = 10;
- // insert data by row-based
- List<JSONObject> rows = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- JSONObject row = new JSONObject();
- row.put(field1Name, i);
- row.put(field2Name, generateFloatVectors(1).get(0));
- // JSON field
- JSONObject info = new JSONObject();
- info.put("row-based-info", i);
- row.put(field3Name, info);
- // extra meta is automatically stored in dynamic field
- row.put("extra_meta", i % 3 == 0);
- row.put(generator.generate(5), 100);
- rows.add(row);
- }
- InsertParam insertRowParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withRows(rows)
- .build();
- R<MutationResult> insertRowResp = client.insert(insertRowParam);
- assertEquals(R.Status.Success.getCode(), insertRowResp.getStatus().intValue());
- System.out.println(rowCount + " rows inserted");
- // insert data by column-based
- List<Long> ids = new ArrayList<>();
- List<JSONObject> infos = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- ids.add(rowCount + i);
- JSONObject obj = new JSONObject();
- obj.put("column-based-info", i);
- obj.put(generator.generate(5), i);
- infos.add(obj);
- }
- List<List<Float>> vectors = generateFloatVectors(rowCount);
- List<InsertParam.Field> fieldsInsert = new ArrayList<>();
- fieldsInsert.add(new InsertParam.Field(field1Name, ids));
- fieldsInsert.add(new InsertParam.Field(field2Name, vectors));
- fieldsInsert.add(new InsertParam.Field(field3Name, infos));
- InsertParam insertColumnsParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFields(fieldsInsert)
- .build();
- R<MutationResult> insertColumnResp = client.insert(insertColumnsParam);
- assertEquals(R.Status.Success.getCode(), insertColumnResp.getStatus().intValue());
- System.out.println(rowCount + " rows inserted");
- // get collection statistics
- R<GetCollectionStatisticsResponse> statR = client.getCollectionStatistics(GetCollectionStatisticsParam
- .newBuilder()
- .withCollectionName(randomCollectionName)
- .withFlush(true)
- .build());
- assertEquals(R.Status.Success.getCode(), statR.getStatus().intValue());
- GetCollStatResponseWrapper stat = new GetCollStatResponseWrapper(statR.getData());
- System.out.println("Collection row count: " + stat.getRowCount());
- // retrieve rows
- String expr = "extra_meta == true";
- List<String> outputFields = Arrays.asList(field3Name, "extra_meta");
- QueryParam queryParam = QueryParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withExpr(expr)
- .withOutFields(outputFields)
- .build();
- R<QueryResults> queryR = client.query(queryParam);
- assertEquals(R.Status.Success.getCode(), queryR.getStatus().intValue());
- QueryResultsWrapper queryResultsWrapper = new QueryResultsWrapper(queryR.getData());
- List<QueryResultsWrapper.RowRecord> records = queryResultsWrapper.getRowRecords();
- System.out.println("Query results:");
- for (QueryResultsWrapper.RowRecord record:records) {
- System.out.println(record);
- Object extraMeta = record.get("extra_meta");
- if (extraMeta != null) {
- System.out.println("'extra_meta' is from dynamic field, value: " + extraMeta);
- }
- }
- // search
- List<List<Float>> targetVectors = generateFloatVectors(2);
- int topK = 5;
- SearchParam searchParam = SearchParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withMetricType(MetricType.L2)
- .withTopK(topK)
- .withVectors(targetVectors)
- .withVectorFieldName(field2Name)
- .withParams("{}")
- .withOutFields(outputFields)
- .build();
- R<SearchResults> searchR = client.search(searchParam);
- assertEquals(R.Status.Success.getCode(), searchR.getStatus().intValue());
- // verify the search result
- SearchResultsWrapper results = new SearchResultsWrapper(searchR.getData().getResults());
- for (int i = 0; i < targetVectors.size(); ++i) {
- List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
- System.out.println("The result of No." + i + " target vector:");
- for (SearchResultsWrapper.IDScore score:scores) {
- System.out.println(score);
- Object extraMeta = score.get("extra_meta");
- if (extraMeta != null) {
- System.out.println("'extra_meta' is from dynamic field, value: " + extraMeta);
- }
- }
- }
- // drop collection
- R<RpcStatus> dropR = client.dropCollection(DropCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- assertEquals(R.Status.Success.getCode(), dropR.getStatus().intValue());
- }
- @Test
- void testHighLevelGet() {
- // collection schema
- String field1Name = "id_field";
- String field2Name = "vector_field";
- FieldType int64PrimaryField = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .build();
- FieldType varcharPrimaryField = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withDataType(DataType.VarChar)
- .withName(field1Name)
- .withMaxLength(128)
- .build();
- FieldType vectorField = FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDimension(dimension)
- .build();
- testCollectionHighLevelGet(int64PrimaryField, vectorField);
- testCollectionHighLevelGet(varcharPrimaryField, vectorField);
- }
- @Test
- void testHighLevelDelete() {
- // collection schema
- String field1Name = "id_field";
- String field2Name = "vector_field";
- FieldType int64PrimaryField = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withAutoID(false)
- .withDataType(DataType.Int64)
- .withName(field1Name)
- .build();
- FieldType varcharPrimaryField = FieldType.newBuilder()
- .withPrimaryKey(true)
- .withDataType(DataType.VarChar)
- .withName(field1Name)
- .withMaxLength(128)
- .build();
- FieldType vectorField = FieldType.newBuilder()
- .withDataType(DataType.FloatVector)
- .withName(field2Name)
- .withDimension(dimension)
- .build();
- testCollectionHighLevelDelete(int64PrimaryField, vectorField);
- testCollectionHighLevelDelete(varcharPrimaryField, vectorField);
- }
- void testCollectionHighLevelGet(FieldType primaryField, FieldType vectorField) {
- // create collection
- String randomCollectionName = generator.generate(10);
- highLevelCreateCollection(primaryField, vectorField, randomCollectionName);
- // insert data
- List<String> primaryIds = new ArrayList<>();
- int rowCount = 10;
- List<JSONObject> rows = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- JSONObject row = new JSONObject();
- row.put(primaryField.getName(), primaryField.getDataType() == DataType.Int64 ? i : String.valueOf(i));
- row.put(vectorField.getName(), generateFloatVectors(1).get(0));
- rows.add(row);
- primaryIds.add(String.valueOf(i));
- }
- InsertParam insertRowParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withRows(rows)
- .build();
- R<MutationResult> insertRowResp = client.insert(insertRowParam);
- Assertions.assertEquals(R.Status.Success.getCode(), insertRowResp.getStatus().intValue());
- testHighLevelGet(randomCollectionName, primaryIds);
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- private static void highLevelCreateCollection(FieldType primaryField, FieldType vectorField, String randomCollectionName) {
- CreateCollectionParam createParam = CreateCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withDescription("test")
- .addFieldType(primaryField)
- .addFieldType(vectorField)
- .build();
- R<RpcStatus> createR = client.createCollection(createParam);
- Assertions.assertEquals(R.Status.Success.getCode(), createR.getStatus().intValue());
- // create index
- CreateIndexParam indexParam = CreateIndexParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withFieldName(vectorField.getName())
- .withIndexName("abv")
- .withIndexType(IndexType.FLAT)
- .withMetricType(MetricType.L2)
- .withExtraParam("{}")
- .build();
- R<RpcStatus> createIndexR = client.createIndex(indexParam);
- Assertions.assertEquals(R.Status.Success.getCode(), createIndexR.getStatus().intValue());
- // load collection
- R<RpcStatus> loadR = client.loadCollection(LoadCollectionParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .build());
- Assertions.assertEquals(R.Status.Success.getCode(), loadR.getStatus().intValue());
- }
- void testCollectionHighLevelDelete(FieldType primaryField, FieldType vectorField) {
- // create collection & buildIndex & loadCollection
- String randomCollectionName = generator.generate(10);
- highLevelCreateCollection(primaryField, vectorField, randomCollectionName);
- // insert data
- List<String> primaryIds = new ArrayList<>();
- int rowCount = 10;
- List<JSONObject> rows = new ArrayList<>();
- for (long i = 0L; i < rowCount; ++i) {
- JSONObject row = new JSONObject();
- row.put(primaryField.getName(), primaryField.getDataType() == DataType.Int64 ? i : String.valueOf(i));
- row.put(vectorField.getName(), generateFloatVectors(1).get(0));
- rows.add(row);
- primaryIds.add(String.valueOf(i));
- }
- InsertParam insertRowParam = InsertParam.newBuilder()
- .withCollectionName(randomCollectionName)
- .withRows(rows)
- .build();
- R<MutationResult> insertRowResp = client.insert(insertRowParam);
- Assertions.assertEquals(R.Status.Success.getCode(), insertRowResp.getStatus().intValue());
- // high level delete
- testHighLevelDelete(randomCollectionName, primaryIds);
- client.dropCollection(DropCollectionParam.newBuilder().withCollectionName(randomCollectionName).build());
- }
- private static void testHighLevelGet(String collectionName, List primaryIds) {
- GetIdsParam getIdsParam = GetIdsParam.newBuilder()
- .withCollectionName(collectionName)
- .withPrimaryIds(primaryIds)
- .build();
- R<GetResponse> getResponseR = client.get(getIdsParam);
- String outPutStr = String.format("collectionName:%s, primaryIds:%s, getResponseR:%s", collectionName, primaryIds, getResponseR.getData());
- System.out.println(outPutStr);
- Assertions.assertEquals(R.Status.Success.getCode(), getResponseR.getStatus().intValue());
- }
- private static void testHighLevelDelete(String collectionName, List primaryIds) {
- DeleteIdsParam deleteIdsParam = DeleteIdsParam.newBuilder()
- .withCollectionName(collectionName)
- .withPrimaryIds(primaryIds)
- .build();
- R<DeleteResponse> deleteResponseR = client.delete(deleteIdsParam);
- String outPutStr = String.format("collectionName:%s, primaryIds:%s, deleteResponseR:%s", collectionName, primaryIds, deleteResponseR);
- System.out.println(outPutStr);
- Assertions.assertEquals(R.Status.Success.getCode(), deleteResponseR.getStatus().intValue());
- }
- }
|