当前位置: 首页 > news >正文

聊聊Spring AI的MilvusVectorStore

本文主要研究一下Spring AI的MilvusVectorStore

示例

pom.xml

		<dependency>
			<groupId>org.springframework.ai</groupId>
			<artifactId>spring-ai-starter-vector-store-milvus</artifactId>
		</dependency>

配置

spring:
  ai:
    vectorstore:
      milvus:
        initialize-schema: true
        databaseName: "default"
        collectionName: "test_collection1"
        embeddingDimension: 1024
        indexType: IVF_FLAT
        metricType: COSINE
        client:
          host: "localhost"
          port: 19530

代码

    @Test
    public void testAddAndSearch() {
        List <Document> documents = List.of(
                new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
                new Document("The World is Big and Salvation Lurks Around the Corner"),
                new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

        // Add the documents to Milvus Vector Store
        vectorStore.add(documents);

        // Retrieve documents similar to a query
        List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
        log.info("results:{}", JSON.toJSONString(results));
    }

输出如下:

results:[{"contentFormatter":{"excludedEmbedMetadataKeys":[],"excludedInferenceMetadataKeys":[],"metadataSeparator":"\n","metadataTemplate":"{key}: {value}","textTemplate":"{metadata_string}\n\n{content}"},"formattedContent":"distance: 0.43509113788604736\nmeta1: meta1\n\nSpring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!","id":"d1c92394-77c8-4c67-9817-0980ad31479d","metadata":{"distance":0.43509113788604736,"meta1":"meta1"},"score":0.5649088621139526,"text":"Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!"},{"contentFormatter":{"$ref":"$[0].contentFormatter"},"formattedContent":"distance: 0.5709311962127686\n\nThe World is Big and Salvation Lurks Around the Corner","id":"65d7ddb3-a735-4dad-9da0-cbba5665b149","metadata":{"distance":0.5709311962127686},"score":0.42906883358955383,"text":"The World is Big and Salvation Lurks Around the Corner"},{"contentFormatter":{"$ref":"$[0].contentFormatter"},"formattedContent":"distance: 0.5936022996902466\nmeta2: meta2\n\nYou walk forward facing the past and you turn back toward the future.","id":"26050d78-3396-4b61-97ea-111249f6d037","metadata":{"distance":0.5936022996902466,"meta2":"meta2"},"score":0.40639767050743103,"text":"You walk forward facing the past and you turn back toward the future."}]

源码

MilvusVectorStoreAutoConfiguration

org/springframework/ai/vectorstore/milvus/autoconfigure/MilvusVectorStoreAutoConfiguration.java

@AutoConfiguration
@ConditionalOnClass({ MilvusVectorStore.class, EmbeddingModel.class })
@EnableConfigurationProperties({ MilvusServiceClientProperties.class, MilvusVectorStoreProperties.class })
@ConditionalOnProperty(name = SpringAIVectorStoreTypes.TYPE, havingValue = SpringAIVectorStoreTypes.MILVUS,
		matchIfMissing = true)
public class MilvusVectorStoreAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(MilvusServiceClientConnectionDetails.class)
	PropertiesMilvusServiceClientConnectionDetails milvusServiceClientConnectionDetails(
			MilvusServiceClientProperties properties) {
		return new PropertiesMilvusServiceClientConnectionDetails(properties);
	}

	@Bean
	@ConditionalOnMissingBean(BatchingStrategy.class)
	BatchingStrategy milvusBatchingStrategy() {
		return new TokenCountBatchingStrategy();
	}

	@Bean
	@ConditionalOnMissingBean
	public MilvusVectorStore vectorStore(MilvusServiceClient milvusClient, EmbeddingModel embeddingModel,
			MilvusVectorStoreProperties properties, BatchingStrategy batchingStrategy,
			ObjectProvider<ObservationRegistry> observationRegistry,
			ObjectProvider<VectorStoreObservationConvention> customObservationConvention) {

		return MilvusVectorStore.builder(milvusClient, embeddingModel)
			.initializeSchema(properties.isInitializeSchema())
			.databaseName(properties.getDatabaseName())
			.collectionName(properties.getCollectionName())
			.embeddingDimension(properties.getEmbeddingDimension())
			.indexType(IndexType.valueOf(properties.getIndexType().name()))
			.metricType(MetricType.valueOf(properties.getMetricType().name()))
			.indexParameters(properties.getIndexParameters())
			.iDFieldName(properties.getIdFieldName())
			.autoId(properties.isAutoId())
			.contentFieldName(properties.getContentFieldName())
			.metadataFieldName(properties.getMetadataFieldName())
			.embeddingFieldName(properties.getEmbeddingFieldName())
			.batchingStrategy(batchingStrategy)
			.observationRegistry(observationRegistry.getIfUnique(() -> ObservationRegistry.NOOP))
			.customObservationConvention(customObservationConvention.getIfAvailable(() -> null))
			.build();
	}

	@Bean
	@ConditionalOnMissingBean
	public MilvusServiceClient milvusClient(MilvusVectorStoreProperties serverProperties,
			MilvusServiceClientProperties clientProperties, MilvusServiceClientConnectionDetails connectionDetails) {

		var builder = ConnectParam.newBuilder()
			.withHost(connectionDetails.getHost())
			.withPort(connectionDetails.getPort())
			.withDatabaseName(serverProperties.getDatabaseName())
			.withConnectTimeout(clientProperties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
			.withKeepAliveTime(clientProperties.getKeepAliveTimeMs(), TimeUnit.MILLISECONDS)
			.withKeepAliveTimeout(clientProperties.getKeepAliveTimeoutMs(), TimeUnit.MILLISECONDS)
			.withRpcDeadline(clientProperties.getRpcDeadlineMs(), TimeUnit.MILLISECONDS)
			.withSecure(clientProperties.isSecure())
			.withIdleTimeout(clientProperties.getIdleTimeoutMs(), TimeUnit.MILLISECONDS)
			.withAuthorization(clientProperties.getUsername(), clientProperties.getPassword());

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getUri())) {
			builder.withUri(clientProperties.getUri());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getToken())) {
			builder.withToken(clientProperties.getToken());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getClientKeyPath())) {
			builder.withClientKeyPath(clientProperties.getClientKeyPath());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getClientPemPath())) {
			builder.withClientPemPath(clientProperties.getClientPemPath());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getCaPemPath())) {
			builder.withCaPemPath(clientProperties.getCaPemPath());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getServerPemPath())) {
			builder.withServerPemPath(clientProperties.getServerPemPath());
		}

		if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getServerName())) {
			builder.withServerName(clientProperties.getServerName());
		}

		return new MilvusServiceClient(builder.build());
	}

	static class PropertiesMilvusServiceClientConnectionDetails implements MilvusServiceClientConnectionDetails {

		private final MilvusServiceClientProperties properties;

		PropertiesMilvusServiceClientConnectionDetails(MilvusServiceClientProperties properties) {
			this.properties = properties;
		}

		@Override
		public String getHost() {
			return this.properties.getHost();
		}

		@Override
		public int getPort() {
			return this.properties.getPort();
		}

	}

}

MilvusVectorStoreAutoConfiguration在spring.ai.vectorstore.typemilvus会启用(matchIfMissing=true),它根据MilvusServiceClientProperties创建PropertiesMilvusServiceClientConnectionDetails,创建TokenCountBatchingStrategy、MilvusServiceClient,最后根据MilvusVectorStoreProperties创建MilvusVectorStore

MilvusServiceClientProperties

org/springframework/ai/vectorstore/milvus/autoconfigure/MilvusServiceClientProperties.java

@ConfigurationProperties(MilvusServiceClientProperties.CONFIG_PREFIX)
public class MilvusServiceClientProperties {

	public static final String CONFIG_PREFIX = "spring.ai.vectorstore.milvus.client";

	/**
	 * Secure the authorization for this connection, set to True to enable TLS.
	 */
	protected boolean secure = false;

	/**
	 * Milvus host name/address.
	 */
	private String host = "localhost";

	/**
	 * Milvus the connection port. Value must be greater than zero and less than 65536.
	 */
	private int port = 19530;

	/**
	 * The uri of Milvus instance
	 */
	private String uri;

	/**
	 * Token serving as the key for identification and authentication purposes.
	 */
	private String token;

	/**
	 * Connection timeout value of client channel. The timeout value must be greater than
	 * zero.
	 */
	private long connectTimeoutMs = 10000;

	/**
	 * Keep-alive time value of client channel. The keep-alive value must be greater than
	 * zero.
	 */
	private long keepAliveTimeMs = 55000;

	/**
	 * Enables the keep-alive function for client channel.
	 */
	// private boolean keepAliveWithoutCalls = false;

	/**
	 * The keep-alive timeout value of client channel. The timeout value must be greater
	 * than zero.
	 */
	private long keepAliveTimeoutMs = 20000;

	/**
	 * Deadline for how long you are willing to wait for a reply from the server. With a
	 * deadline setting, the client will wait when encounter fast RPC fail caused by
	 * network fluctuations. The deadline value must be larger than or equal to zero.
	 * Default value is 0, deadline is disabled.
	 */
	private long rpcDeadlineMs = 0; // Disabling deadline

	/**
	 * The client.key path for tls two-way authentication, only takes effect when "secure"
	 * is True.
	 */
	private String clientKeyPath;

	/**
	 * The client.pem path for tls two-way authentication, only takes effect when "secure"
	 * is True.
	 */
	private String clientPemPath;

	/**
	 * The ca.pem path for tls two-way authentication, only takes effect when "secure" is
	 * True.
	 */
	private String caPemPath;

	/**
	 * server.pem path for tls one-way authentication, only takes effect when "secure" is
	 * True.
	 */
	private String serverPemPath;

	/**
	 * Sets the target name override for SSL host name checking, only takes effect when
	 * "secure" is True. Note: this value is passed to grpc.ssl_target_name_override
	 */
	private String serverName;

	/**
	 * Idle timeout value of client channel. The timeout value must be larger than zero.
	 */
	private long idleTimeoutMs = TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS);

	/**
	 * The username and password for this connection.
	 */
	private String username = "root";

	/**
	 * The password for this connection.
	 */
	private String password = "milvus";

	//......
}	

MilvusServiceClientProperties提供了spring.ai.vectorstore.milvus.client的配置,可以设置host、port、connectTimeoutMs、username、password等

PropertiesMilvusServiceClientConnectionDetails

org/springframework/ai/vectorstore/milvus/autoconfigure/MilvusVectorStoreAutoConfiguration.java

	static class PropertiesMilvusServiceClientConnectionDetails implements MilvusServiceClientConnectionDetails {

		private final MilvusServiceClientProperties properties;

		PropertiesMilvusServiceClientConnectionDetails(MilvusServiceClientProperties properties) {
			this.properties = properties;
		}

		@Override
		public String getHost() {
			return this.properties.getHost();
		}

		@Override
		public int getPort() {
			return this.properties.getPort();
		}

	}

PropertiesMilvusServiceClientConnectionDetails实现了MilvusServiceClientConnectionDetails接口,适配了getHost、getPort方法

MilvusVectorStoreProperties

org/springframework/ai/vectorstore/milvus/autoconfigure/MilvusVectorStoreProperties.java

@ConfigurationProperties(MilvusVectorStoreProperties.CONFIG_PREFIX)
public class MilvusVectorStoreProperties extends CommonVectorStoreProperties {

	public static final String CONFIG_PREFIX = "spring.ai.vectorstore.milvus";

	/**
	 * The name of the Milvus database to connect to.
	 */
	private String databaseName = MilvusVectorStore.DEFAULT_DATABASE_NAME;

	/**
	 * Milvus collection name to store the vectors.
	 */
	private String collectionName = MilvusVectorStore.DEFAULT_COLLECTION_NAME;

	/**
	 * The dimension of the vectors to be stored in the Milvus collection.
	 */
	private int embeddingDimension = MilvusVectorStore.OPENAI_EMBEDDING_DIMENSION_SIZE;

	/**
	 * The type of the index to be created for the Milvus collection.
	 */
	private MilvusIndexType indexType = MilvusIndexType.IVF_FLAT;

	/**
	 * The metric type to be used for the Milvus collection.
	 */
	private MilvusMetricType metricType = MilvusMetricType.COSINE;

	/**
	 * The index parameters to be used for the Milvus collection.
	 */
	private String indexParameters = "{\"nlist\":1024}";

	/**
	 * The ID field name for the collection.
	 */
	private String idFieldName = MilvusVectorStore.DOC_ID_FIELD_NAME;

	/**
	 * Boolean flag to indicate if the auto-id is used.
	 */
	private boolean isAutoId = false;

	/**
	 * The content field name for the collection.
	 */
	private String contentFieldName = MilvusVectorStore.CONTENT_FIELD_NAME;

	/**
	 * The metadata field name for the collection.
	 */
	private String metadataFieldName = MilvusVectorStore.METADATA_FIELD_NAME;

	/**
	 * The embedding field name for the collection.
	 */
	private String embeddingFieldName = MilvusVectorStore.EMBEDDING_FIELD_NAME;

	//......

	public enum MilvusMetricType {

		/**
		 * Invalid metric type
		 */
		INVALID,
		/**
		 * Euclidean distance
		 */
		L2,
		/**
		 * Inner product
		 */
		IP,
		/**
		 * Cosine distance
		 */
		COSINE,
		/**
		 * Hamming distance
		 */
		HAMMING,
		/**
		 * Jaccard distance
		 */
		JACCARD

	}

	public enum MilvusIndexType {

		INVALID, FLAT, IVF_FLAT, IVF_SQ8, IVF_PQ, HNSW, DISKANN, AUTOINDEX, SCANN, GPU_IVF_FLAT, GPU_IVF_PQ, BIN_FLAT,
		BIN_IVF_FLAT, TRIE, STL_SORT

	}

}	

MilvusVectorStoreProperties提供了spring.ai.vectorstore.milvus的配置,主要是配置databaseName、collectionName、embeddingDimension(默认1536)、indexType(默认IVF_FLAT)、metricType(默认COSINE)

CommonVectorStoreProperties

org/springframework/ai/vectorstore/properties/CommonVectorStoreProperties.java

public class CommonVectorStoreProperties {

	/**
	 * Vector stores do not initialize schema by default on application startup. The
	 * applications explicitly need to opt-in for initializing the schema on startup. The
	 * recommended way to initialize the schema on startup is to set the initialize-schema
	 * property on the vector store. See {@link #setInitializeSchema(boolean)}.
	 */
	private boolean initializeSchema = false;

	public boolean isInitializeSchema() {
		return this.initializeSchema;
	}

	public void setInitializeSchema(boolean initializeSchema) {
		this.initializeSchema = initializeSchema;
	}

}

CommonVectorStoreProperties定义了initializeSchema属性,代表说是否需要在启动的时候初始化schema

小结

Spring AI提供了spring-ai-starter-vector-store-milvus用于自动装配MilvusVectorStore。要注意的是embeddingDimension默认是1536,如果出现io.milvus.exception.ParamException: Incorrect dimension for field 'embedding': the no.0 vector's dimension: 1024 is not equal to field's dimension: 1536,那么需要重建schema,把embeddingDimension设置为1024。

doc

  • milvus

相关文章:

  • 前端网络请求与资源加载优化实战指南
  • 【AI提示词】因果溯源大师
  • SpringBoot学生成绩管理系统设计与实现
  • [Linux][经验总结]vi编辑文件中文乱码,但cat查看却显示正常处理方法
  • 国网B接口注册流程详解以及注册失败原因(电网B接口)
  • 明远智睿RK3588开发板助力工业机器智能化升级
  • 通过世界排名第一的免费开源ERP,构建富有弹性的智能供应链
  • 高级:消息队列面试题精讲
  • 【学Rust写CAD】36 颜色插值函数(alpha256.rs补充方法)
  • Vue3实战二、搭建Vue3+ElementPlus项目教程
  • Scala 转义字符
  • AI赋能ArcGIS Pro——水系网络AI智能提取 | GIS人工智能制图技术解析
  • 洛谷 P3367 【模板】并查集 C++
  • [原创](Modern C++)现代C++的关键性概念: std::move()可以理解为把数据进行剪切再粘贴.
  • BGP路由协议之解决 IBGP 水平分割带来的问题
  • 【Tauri2】016——后端Invoke结构体和invoke_key
  • opus+ffmpeg+c++实现录音
  • Windwos的DNS解析命令nslookup
  • Linux系统的不同发行版的常用命令
  • 大储EMS能量管理系统解决方案:助力企业实现智慧能源转型
  • 贵州仁怀通报“正新鸡排鸡腿里全是蛆”:已对同类产品封存送检
  • 巴菲特最新调仓:一季度大幅抛售银行股,再现保密仓位
  • 今年有望投产里程已近3000公里,高铁冲刺谁在“狂飙”?
  • 7月纽约举办“上海日”,上海大剧院舞剧《白蛇》连演三场
  • 西安市未央区委书记刘国荣已任西咸新区党工委书记
  • 美国明尼苏达州发生山火,过火面积超80平方公里