hibernate 在Java中将openAI嵌入存储到postgres

r3i60tvu  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(88)

我无法将嵌入存储到postgresql数据库。
我正在使用Open AI API计算Java中的嵌入。

EmbeddingResult embeddingResult = openAIService.createEmbedding(embeddingInput);
List<Double> embeddingsList = embeddingResult.getData().get(0).getEmbedding();

字符串
返回List<Double>
现在我需要将它存储到Postgres数据库中。我需要将它存储到一个列中,作为一个向量(1536)。
x1c 0d1x的数据
我尝试创建自己的类- AttributeConverter,以便Hibernate可以将List<Double>作为PostgreSQL数组/向量处理。

@Converter(autoApply = true)
public class ListToDoubleArrayConverter implements AttributeConverter<List<Double>, Double[]> {

    @Override
    public Double[] convertToDatabaseColumn(List<Double> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return new Double[0];
        }
        return attribute.toArray(new Double[attribute.size()]);
    }

    @Override
    public List<Double> convertToEntityAttribute(Double[] dbData) {
        if (dbData == null || dbData.length == 0) {
            return new ArrayList<>();
        }
        return Arrays.asList(dbData);
    }
}


并使用它

@Entity
@Data
@Table(name = "explicit_questions")
@EntityListeners(AuditingEntityListener.class)
public class ExplicitQuestion implements IBaseModel {

    ...

    @Convert(converter = ListToDoubleArrayConverter.class)
    private List<Double> embedding;


我得到了:o.h.engine.jdbc.spi.SqlExceptionHelper:ERROR:column“embedding”is of type vector but expression is of type bytea提示:您需要重写或强制转换表达式。
我试

@Column(columnDefinition = "jsonb")
@Type(type = "jsonb")
private List<Double> embedding;


我可以存储嵌入,但我无法获取。
我也试着定义我自己的类型。

@TypeDef(
    name = "double-array",
    typeClass = DoubleArrayType.class
)
public class ExplicitQuestion... {

    @Type(type = "double-array")
    @Column(
        name = "embeddings", 
        columnDefinition = "double precision[]"
    )
    private List<Double> embeddings;

}


但都不管用。
我使用spring的PagingAndSortingRepository来自动生成SQL。我也试着写我自己的:

@Query(value = "UPDATE explicit_questions set embedding = :embedding where id = :id", nativeQuery = true)
void createEmbedding(@Param("id") Long id, @Param("embedding") Double[] embedding);


我知道我可以将嵌入存储到单独的表中,但是这样做太慢了。

whitzsjs

whitzsjs1#

我在这里找到了解决方案What JPA + Hibernate data type should I use to support the vector extension in a PostgreSQL database?

import com.fasterxml.jackson.annotation.JsonInclude;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.*;

@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
@TypeDef(name = "json", typeClass = JsonType.class)
public class ExplicitQuestion implements IBaseModel {

    ...

    @Basic
    @Type(type = "json")
    @Column(name = "embedding", columnDefinition = "vector")
    private List<Double> embedding;
}

字符串

相关问题