AI开发跃迁指南(第三章:第四维度3——weaviate集合、对象管理从零代码开始详解)
我们使用weaviate cloud来做演示,其相关使用信息已经在AI开发跃迁指南(第三章:第四维度2——weaviate cloud、weaviate docker安装配置及使用连接示例)详细说明。
1.基本信息及依赖
本次实例我们使用java客户端做演示,但是weaviate 客户端对python和js支持的比较好,java客户端还缺失很多功能,部分代码演示我们将使用python客户端的V4版本。
- java版本: 需要依赖
JDK8+
- pom依赖:
<dependency><groupId>io.weaviate</groupId><artifactId>client</artifactId><version>4.7.0</version> <!-- Check latest version --> </dependency>
- weaviate client创建:
package com.service;import io.weaviate.client.Config; import io.weaviate.client.WeaviateAuthClient; import io.weaviate.client.WeaviateClient; import io.weaviate.client.base.Result; import io.weaviate.client.v1.auth.exception.AuthException; import io.weaviate.client.v1.schema.model.DataType; import io.weaviate.client.v1.schema.model.Property; import io.weaviate.client.v1.schema.model.WeaviateClass;public class WeaviateTest {public void createClient() {String scheme = "https";// 所要使用的cluster的endpoint和apiKeyString host = "xxxxxxxxx";String apiKey = "xxxxxxxxx";Config config = new Config(scheme, host);try {WeaviateClient client = WeaviateAuthClient.apiKey(config, apiKey);createActorColl(client);} catch (AuthException e) {e.printStackTrace();}}...... }
2.集合管理
2.1.创建集合
2.1.1.代码演示
public void createActorColl(WeaviateClient client) {String className = "Actor";// 定义对象属性Property nameProperty = Property.builder().name("basicInfo").description("基本信息").dataType(List.of(DataType.TEXT)).build();Property workProperty = Property.builder().name("work").description("作品信息").dataType(List.of(DataType.TEXT)).build();// 添加属性到对象中WeaviateClass articleClass = WeaviateClass.builder().className(className).description("演员集合").properties(Arrays.asList(nameProperty, workProperty)).build();Result<Boolean> result = client.schema().classCreator().withClass(articleClass).run();var re = result.getResult();System.out.println(re);}
输出结果:
true
weaviate cloud中查看点击集合按钮,发现也已经创建成功:
2.1.2.核心分析
创建集合的核心代码为client.schema().classCreator().withClass(articleClass).run();
其中.schema()
表示为对集合操作,.classCreator()
表示为是创建集合操作,.withClass(articleClass)
用来配置集合的相关信息。
WeaviateClass更多方法:
方法 | 作用 |
---|---|
.vectorizer("text2vec-openai") | 指定矢量化器 |
.vectorIndexType("hnsw") | 设置向量索引类型 |
.vectorIndexConfig(createBqIndexConfig) | 设置向量索引参数 |
2.2.读取集合
2.2.1.代码演示
public void readColl(WeaviateClient client) {String className = "Actor";// 查询集合信息Result<WeaviateClass> result = client.schema().classGetter().withClassName(className).run();// 将结果转为jsonString json = new GsonBuilder().setPrettyPrinting().create().toJson(result.getResult());System.out.println(json);}
返回结果(部分):
{"class": "Actor","description": "演员集合","invertedIndexConfig": {"bm25": {"k1": 1.2,"b": 0.75},"stopwords": {"preset": "en"},"cleanupIntervalSeconds": 60},"properties": [{"name": "basicInfo","dataType": ["text"],"description": "基本信息","tokenization": "word","indexFilterable": true,"indexSearchable": true},{"name": "work","dataType": ["text"],"description": "作品信息","tokenization": "word","indexFilterable": true,"indexSearchable": true}],"vectorIndexConfig": {"distance": "cosine","ef": -1,"efConstruction": 128,"maxConnections": 32,"dynamicEfMin": 100,"dynamicEfMax": 500,"dynamicEfFactor": 8,"vectorCacheMaxObjects": 1000000000000,"flatSearchCutoff": 40000,"cleanupIntervalSeconds": 300,"skip": false,"pq": {"enabled": false,"bitCompression": false,"segments": 0,"centroids": 256,"trainingLimit": 100000,"encoder": {"type": "kmeans","distribution": "log-normal"}},"bq": {"enabled": false}},"shardingConfig": {"actualCount": 1,"actualVirtualCount": 128,"desiredCount": 1,"desiredVirtualCount": 128,"function": "murmur3","key": "_id","strategy": "hash","virtualPerPhysical": 128},"vectorIndexType": "hnsw","vectorizer": "none","replicationConfig": {"factor": 1},"multiTenancyConfig": {"enabled": false,"autoTenantCreation": false}
}Process finished with exit code 0
2.2.2.核心分析
.classGetter()
方法给定集合名称,查询单个集合信息,.getter()
方法返回所有的集合信息
Result<Schema> result = client.schema().getter().run();String json = new GsonBuilder().setPrettyPrinting().create().toJson(result.getResult());
System.out.println(json);
2.3.更新集合
java客户端中还未开发此功能,我们使用python代码所简单的演示。
from weaviate.classes.config import Reconfigure# Get the Actor collection object
articles = client.collections.get("Actor")# Update the collection configuration
articles.config.update(# Note, use Reconfigure here (not Configure)inverted_index_config=Reconfigure.inverted_index(stopwords_removals=["a", "the"]
2.4.删除集合
public void delColl(WeaviateClient client) {String className = "Actor";Result<Boolean> result = client.schema().classDeleter().withClassName(className).run();System.out.println(result.getResult());}
执行结果:
True
2.5.集合添加属性
给Article集合增加一个属性:
public void addCollProperty(WeaviateClient client) {Property property = Property.builder().dataType(List.of(DataType.INT)).name("age").build();Result<Boolean> result = client.schema().propertyCreator().withClassName("Article").withProperty(property).run();System.out.println(result.getResult());}
执行结果:
True
Article集合从之前的两个属性变为了三个:
3. 对象管理
weaviate对象是其集合中的数据实体,其中包括原始数据和向量数据两部分。
3.1.创建对象
public void createObject(WeaviateClient client) {String className = "Actor";var properties = new HashMap<String, Object>() {{put("basicInfo", "周迅是中国影坛最具实力的女演员之一,出生日期:1974年10月18日;出生地:浙江省衢州市;代表奖项:金马奖、金像奖、金鸡奖、百花奖等多项影后;以灵动的演技和独特的气质著称。她擅长刻画复杂角色,戏路宽广从文艺片到商业片均有经典作品。");put("work", "《苏州河》(2000年)饰演“牡丹”/“美美”,凭借此片获得巴黎国际电影节最佳女主角。《如果·爱》(2005年)饰演“孙纳”,获金马奖、金像奖最佳女主角。《画皮》系列(2008/2012年)饰演狐妖“小唯”,商业与艺术结合的代表作。《风声》(2009年)饰演特工“顾晓梦”,演技备受赞誉。");}};Result<WeaviateObject> result = client.data().creator().withClassName(className).withProperties(properties).run();String json = new GsonBuilder().setPrettyPrinting().create().toJson(result.getResult());System.out.println(json);}
执行结果:
{"id": "f8d46c3a-2553-4483-b16a-7bafb9bcbcd1","class": "Actor","creationTimeUnix": 1746779863194,"lastUpdateTimeUnix": 1746779863194,"properties": {"basicInfo": "周迅是中国影坛最具实力的女演员之一,出生日期:1974年10月18日;出生地:浙江省衢州市;代表奖项:金马奖、金像奖、金鸡奖、百花奖等多项影后;以灵动的演技和独特的气质著称。她擅长刻画复杂角色,戏路宽广从文艺片到商业片均有经典作品。","work": "《苏州河》(2000年)饰演“牡丹”/“美美”,凭借此片获得巴黎国际电影节最佳女主角。《如果?爱》(2005年)饰演“孙纳”,获金马奖、金像奖最佳女主角。《画皮》系列(2008/2012年)饰演狐妖“小唯”,商业与艺术结合的代表作。《风声》(2009年)饰演特工“顾晓梦”,演技备受赞誉。"}
}
.data().creator()
为创建集合对象数据的核心方法。其返回值为ObjectCreator
类型,此类型中可以添加对象所属集合、属性值等信息,也可通过withVector()
自定义向量;withID()
自定义Id等。
3.2.批量导入
批量导入需要用到ObjectsBatcher
类,其中放入多个对象,一次批量提交。
public void batchImportObject(WeaviateClient client) {String className = "Actor"; // Replace with your class nameList<Map<String, Object>> dataObjs = new ArrayList<>();var propertie1 = new HashMap<String, Object>() {{put("basicInfo", "杨幂是85后花旦中的顶流代表,出生日期:1986年9月12日;出生地:北京市;代表奖项:上海电视节白玉兰奖提名、休斯顿国际电影节最佳女主角;以高产量和高话题度闻名。早期以古装剧走红,后转型制片人,成立公司嘉行传媒,培养新人。");put("work", "《仙剑奇侠传三》(2009年)分饰“唐雪见”和“夕瑶”,奠定人气基础。《宫锁心玉》(2011年)饰演穿越女“洛晴川”,爆红并开启“穿越剧”热潮。《小时代》系列(2013-2015年)饰演“林萧”,争议与票房并存。");}};var propertie2 = new HashMap<String, Object>() {{put("basicInfo", "刘亦菲是中国内地知名女演员,出生日期:1987年8月25日;出生地:湖北省武汉市;代表奖项:澳门国际电影节最佳女主角、东京国际电影节中国电影周最佳女主角;因清冷仙气的外形和古装扮相被誉为“神仙姐姐”。早年以电视剧走红,后转战电影并进军好莱坞。");put("work", "《天龙八部》(2003年)饰演“王语嫣”,获封“神仙姐姐”称号。《仙剑奇侠传》(2005年)饰演“赵灵儿”,成为一代人的青春记忆。《神雕侠侣》(2006年)饰演“小龙女”,奠定古装女神地位。《梦华录》(2022年)饰演“赵盼儿”,时隔16年回归电视剧,口碑热度双丰收。");}};// 两个对象加入的listdataObjs.add(propertie1);dataObjs.add(propertie2);ObjectsBatcher batcher = client.batch().objectsBatcher();// 将多个对象添加到batcher中for (Map<String, Object> properties : dataObjs) {batcher.withObject(WeaviateObject.builder().className(className).properties(properties)// .tenant("tenantA") // 如果启用了多租户,请指定要添加对象的租户.build());}batcher.run();}
3.3.读取对象(根据ID)
public void readObject(WeaviateClient client) {String className = "Actor";Result<List<WeaviateObject>> result = client.data().objectsGetter().withClassName(className).withID("f8d46c3a-2553-4483-b16a-7bafb9bcbcd1").run();System.out.println(result.getResult());}
执行结果:
[WeaviateObject(id=f8d46c3a-2553-4483-b16a-7bafb9bcbcd1, className=Actor, creationTimeUnix=1746779863194, lastUpdateTimeUnix=1746779863194, properties={basicInfo=周迅是中国影坛最具实力的女演员之一,出生日期:1974年10月18日;出生地:浙江省衢州市;代表奖项:金马奖、金像奖、金鸡奖、百花奖等多项影后;以灵动的演技和独特的气质著称。她擅长刻画复杂角色,戏路宽广从文艺片到商业片均有经典作品。, work=《苏州河》(2000年)饰演“牡丹”/“美美”,凭借此片获得巴黎国际电影节最佳女主角。《如果?爱》(2005年)饰演“孙纳”,获金马奖、金像奖最佳女主角。《画皮》系列(2008/2012年)饰演狐妖“小唯”,商业与艺术结合的代表作。《风声》(2009年)饰演特工“顾晓梦”,演技备受赞誉。}, additional=null, vector=null, vectors=null, vectorWeights=null, tenant=null)]
3.4.删除对象(根据ID)
String idToDelete = "..."; //client.data().deleter().withClassName("Actor") // Class of the object to be deleted.withID(idToDelete).run();