milvus-logo
LFAI
< Docs
  • Java
    • v1

search()

The MilvusClient interface. This method conducts an approximate nearest neighbor (ANN) search on a vector field and pairs up with a Boolean expression to conduct filtering on scalar fields before searching.

R<SearchResults> search(SearchParam requestParam);

SearchParam

Use the SearchParam.Builder to construct a SearchParam object.

import io.milvus.param.dml.SearchParam;
SearchParam.Builder builder = SearchParam.newBuilder();

Methods of SearchParam.Builder:

Method

Description

Parameters

withCollectionName(collectionName)

Set the collection name. Collection name cannot be empty or null.

collectionName: The target collection name.

withDatabaseName(String databaseName)

Sets the database name. database name can be null for default database.

databaseName: The database name.

withConsistencyLevel(ConsistencyLevelEnum consistencyLevel)

Sets the search consistency level(Optional).
If the level is not set, will use the default consistency level of the collection.

consistencyLevel: The consistency level used in the search.

withPartitionNames(List<String> partitionNames)

Sets partition names list to specify search scope (Optional).

partitionNames: The name list of partitions to be searched.

addPartitionName(String partitionName)

Adds a partition to specify search scope (Optional).

partitionName: A partition name to be searched.

withOutFields(List<String> outFields)

Specifies output scalar fields (Optional).


outFields: The name list of fields to be outputed.

addOutField(String fieldName)

Specifies an output scalar field (Optional).

fieldName: An output field name.

withExpr(String expr)

Set the expression to filter scalar fields before searching(Optional).For more information please refer to this doc.

expr: The expression to filter scalar fields.

withMetricType(MetricType metricType)

Set metric type of ANN search.
Default value is MetricType.None, which means let the server determine the defaul metric type. Please refer to MetricType in Misc.

metricType: The metric type to search.

withVectorFieldName(String vectorFieldName)

Set target vector field by name. Field name cannot be empty or null.

vectorFieldName: The target vector field name to do ANN search.

withTopK(Integer topK)

Set topK value of ANN search.
Avaiable range: [1, 16384]

topK: The topk value.

withVectors(List<?> vectors)

Set the target vectors. Up to 16384 vectors allowed.

vectors:
- If target field type is FloatVector, List< List<Float>gt; is required.
- If target field type is BinaryVector vector, List<ByteBuffer> is required.

withRoundDecimal(Integer decimal)

Specifies the decimal place for returned distance.
Avaiable range: [-1, 6]
Default value is -1, return all digits.

decimal: How many digits reserved after the decimal point.

withParams(String params)

Specifies the parameters of search in JSON format. The followings are valid keys of param:
1. special parameters for index, such as "nprobe", "ef", "searchk"
2. metric type with key "metric
type" and a string value such as "L2", "IP".
3. offset for pagination with key "offset" and an integer value

params: A JSON format string for extra parameters.

withIgnoreGrowing(Boolean ignoreGrowing)

Ignore the growing segments to get best search performance. For the user case that don't require data visibility.
Default is False.

ignoreGrowing: Ignore growing segments or not.

build()

Construct a SearchParam object.

N/A

The SearchParam.Builder.build() can throw the following exceptions:

  • ParamException: error if the parameter is invalid.

Returns

This method catches all the exceptions and returns an R<SearchResults> object.

  • If the API fails on the server side, it returns the error code and message from the server.

  • If the API fails by RPC exception, it returns R.Status.Unknown and the error message of the exception.

  • If the API succeeds, it returns valid SearchResults held by the R template. You can use SearchResultsWrapper to get the results.

SearchResultsWrapper

A tool class to encapsulate the SearchResults.

import io.milvus.response.SearchResultsWrapper;
SearchResultsWrapper wrapper = new SearchResultsWrapper(searchResults);

Methods of SearchResultsWrapper:

Method

Description

Parameters

Returns

getFieldData(String fieldName, int indexOfTarget)

Gets data for an output field which is specified by SearchParam.

Throws ParamException if the field doesn't exist or indexOfTarget is illegal.

fieldName: A field name which is specified by the withOutFields() of SearchParam.

indexOfTarget: The order number of a target vector.

  • Return List<List<Float>gt; for FloatVector field.
  • Return List<ByteBuffer> for BinaryVector field.
  • Return List<Long> for int64 field.
  • Return List<Integer> for int32/int16/int8 field.
  • Return List<Boolean> for boolean field.
  • Return List<Float> for float field.
  • Return List<Double> for double field.
  • Return List<String> for varchar field.

getIDScore(int indexOfTarget)

Gets ID-score pairs returned by search().

Throws ParamException if the indexOfTarget is illegal.Throws IllegalResponseException if the returned results are illegal.

indexOfTarget: The order number of a target vector.

List<IDScore>

getRowRecords(int indexOfTarget)

Gets row records from the search result.

The ID is put into a QueryResultsWrapper.RowRecord with key "id".

The distance is put into a QueryResultsWrapper.RowRecord with key "distance".

indexOfTarget: The order number of a target vector.

List<QueryResultsWrapper.RowRecord>

IDScore

A tool class to hold a pair of ID and distance, along with values of the output fields.

Methods of SearchResultsWrapper.IDScore:

Method

Description

Returns

getLongID()

Get integer ID if the primary key type is Int64.

long

getStrID()

Get string ID if the primary key type is VarChar.

String

getScore()

Get distance value.

float

get(String keyName)

Get a value by a key name. If the key name is a field name, return the value of this field.If the key name is in the dynamic field, return the value from the dynamic field.Throws ParamException if the key name doesn't exist.

Object

Example

import io.milvus.param.dml.*;
import io.milvus.response.SearchResultsWrapper;
import io.milvus.grpc.SearchResults;

SearchParam param = SearchParam.newBuilder()
        .withCollectionName(COLLECTION_NAME)
        .withMetricType(MetricType.IP)
        .withTopK(10)
        .withVectors(targetVectors)
        .withVectorFieldName("field1")
        .withConsistencyLevel(ConsistencyLevelEnum.EVENTUALLY)
        .withParams("{\"nprobe\":10,\"offset\":2, \"limit\":3}")
        .build();
R<SearchResults> response = client.search(param)
if (response.getStatus() != R.Status.Success.getCode()) {
    System.out.println(response.getMessage());
}

SearchResultsWrapper wrapper = new SearchResultsWrapper(response.getData().getResults());
System.out.println("Search results:");
for (int i = 0; i < targetVectors.size(); ++i) {
    List<SearchResultsWrapper.IDScore> scores = results.getIDScore(i);
    for (SearchResultsWrapper.IDScore score:scores) {
        System.out.println(score);
    }
}
Feedback

Was this page helpful?