我应该使用什么JPA + Hibernate数据类型来支持PostgreSQL数据库中的vector扩展?

i7uaboj4  于 2023-08-06  发布在  PostgreSQL
关注(0)|答案(1)|浏览(196)

我应该使用什么JPA + Hibernate数据类型来支持PostgreSQL数据库中的向量扩展,以便它允许我使用JPA实体创建嵌入?

CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));

字符串

u4dcyp6a

u4dcyp6a1#

您可以使用vladmihalcea Hibernate类型将向量类型转换为List,因此可以使用JpaRepository保存或查询。
1.将依赖项添加到pom.xml文件:

<dependency>
  <groupId>io.hypersistence</groupId>
  <artifactId>hypersistence-utils-hibernate-55</artifactId>
  <version>3.5.0</version>
</dependency>

字符串
1.创建 Item 类:

import com.fasterxml.jackson.annotation.JsonInclude;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence.*;
import java.util.List;

@Data
@NoArgsConstructor
@Entity
@Table(name = "items")
@JsonInclude(JsonInclude.Include.NON_NULL)
@TypeDef(name = "json", typeClass = JsonType.class)
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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


1.创建一个支持保存和查找的JpaRepository接口。您可以使用本机SQL编写自定义findNearestNeighbors方法

import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item, Long> {

    // Find nearest neighbors by a vector, for example value = "[1,2,3]"
    // This also works, cast is equals to the :: operator in postgresql
    //@Query(nativeQuery = true, value = "SELECT * FROM items ORDER BY embedding <-> cast(? as vector) LIMIT 5")
    @Query(nativeQuery = true, value = "SELECT * FROM items ORDER BY embedding <-> ? \\:\\:vector LIMIT 5")
    List<Item> findNearestNeighbors(String value);

    // Find nearest neighbors by a record in the same table
    @Query(nativeQuery = true, value = "SELECT * FROM items WHERE id != :id ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = :id) LIMIT 5")
    List<Item> findNearestNeighbors(Long id);
}


1.测试创建、查询和findNearestNeighbors:

@Autowired
private ItemRepository itemRepository;

@Test
@Rollback(false)
@Transactional
public void createItem() {
    Item item = new Item();
    Random rand = new Random();
    List<Double> embedding = new ArrayList<>();
    for (int i = 0; i < 3; i++)
        embedding.add(rand.nextDouble());
    item.setEmbedding(embedding);
    itemRepository.save(item);
}

@Test
public void loadItems() {
    final List<Item> items = itemRepository.findAll();
    System.out.println(items);
}

@Test
public void findNearestNeighbors() {
    final String value = "[0.1, 0.2, 0.3]";
    final List<Item> items = itemRepository.findNearestNeighbors(value);
    System.out.println(items);
}

相关问题