|
1 | 1 | package io.weaviate.client6.v1.api.collections.vectorindex; |
2 | 2 |
|
| 3 | +import java.io.IOException; |
3 | 4 | import java.util.function.Function; |
4 | 5 |
|
| 6 | +import com.google.gson.Gson; |
| 7 | +import com.google.gson.JsonObject; |
| 8 | +import com.google.gson.JsonParser; |
| 9 | +import com.google.gson.TypeAdapter; |
| 10 | +import com.google.gson.TypeAdapterFactory; |
5 | 11 | import com.google.gson.annotations.SerializedName; |
| 12 | +import com.google.gson.internal.Streams; |
| 13 | +import com.google.gson.reflect.TypeToken; |
| 14 | +import com.google.gson.stream.JsonReader; |
| 15 | +import com.google.gson.stream.JsonWriter; |
6 | 16 |
|
7 | 17 | import io.weaviate.client6.v1.api.collections.VectorIndex; |
8 | 18 | import io.weaviate.client6.v1.internal.ObjectBuilder; |
@@ -64,4 +74,47 @@ public Dynamic build() { |
64 | 74 | return new Dynamic(this); |
65 | 75 | } |
66 | 76 | } |
| 77 | + |
| 78 | + public static enum CustomTypeAdapterFactory implements TypeAdapterFactory { |
| 79 | + INSTANCE; |
| 80 | + |
| 81 | + @SuppressWarnings("unchecked") |
| 82 | + @Override |
| 83 | + public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { |
| 84 | + var rawType = type.getRawType(); |
| 85 | + if (!Dynamic.class.isAssignableFrom(rawType)) { |
| 86 | + return null; |
| 87 | + } |
| 88 | + |
| 89 | + final var hnswAdapter = gson.getDelegateAdapter(VectorIndex.CustomTypeAdapterFactory.INSTANCE, |
| 90 | + TypeToken.get(Hnsw.class)); |
| 91 | + final var flatAdapter = gson.getDelegateAdapter(VectorIndex.CustomTypeAdapterFactory.INSTANCE, |
| 92 | + TypeToken.get(Flat.class)); |
| 93 | + |
| 94 | + return (TypeAdapter<T>) new TypeAdapter<Dynamic>() { |
| 95 | + |
| 96 | + @Override |
| 97 | + public void write(JsonWriter out, Dynamic value) throws IOException { |
| 98 | + |
| 99 | + var dynamic = new JsonObject(); |
| 100 | + |
| 101 | + dynamic.addProperty("threshold", value.threshold); |
| 102 | + dynamic.add("hnsw", hnswAdapter.toJsonTree(value.hnsw)); |
| 103 | + dynamic.add("flat", flatAdapter.toJsonTree(value.flat)); |
| 104 | + |
| 105 | + Streams.write(dynamic, out); |
| 106 | + } |
| 107 | + |
| 108 | + @Override |
| 109 | + public Dynamic read(JsonReader in) throws IOException { |
| 110 | + var jsonObject = JsonParser.parseReader(in).getAsJsonObject(); |
| 111 | + |
| 112 | + var hnsw = hnswAdapter.fromJsonTree(jsonObject.get("hnsw")); |
| 113 | + var flat = flatAdapter.fromJsonTree(jsonObject.get("flat")); |
| 114 | + var threshold = jsonObject.get("threshold").getAsLong(); |
| 115 | + return new Dynamic(hnsw, flat, threshold); |
| 116 | + } |
| 117 | + }.nullSafe(); |
| 118 | + } |
| 119 | + } |
67 | 120 | } |
0 commit comments