多重查询与筛选

使用 OpenAI API 的 Embeddings 入门

Emmanuel Pire

Senior Software Engineer, DataCamp

基于多数据点的电影推荐

 

  • Terrifier(id: 's8170'
  • Strawberry Shortcake: Berry Bitty Adventures(id: 's8103'
使用 OpenAI API 的 Embeddings 入门

多条查询文本

reference_ids = ['s8170', 's8103']


reference_texts = collection.get(ids=reference_ids)["documents"]
result = collection.query( query_texts=reference_texts, n_results=3 )
使用 OpenAI API 的 Embeddings 入门

多条查询文本的结果

{'ids': [['s8170', 's6939', 's7000'],['s8103', 's2968', 's3085']],
 'embeddings': None,
 'documents': [['Title: Terrifier (Movie)...',
   'Title: Haunters: The Art of the Scare (Movie)...',
   'Title: Horror Story (Movie)...'],
  ["Title: Strawberry Shortcake: Berry Bitty Adventures (TV Show)...",
   "Title: Shopkins (TV Show)...",
   "Title: Rainbow Ruby (TV Show)..."]],
 'metadatas': [[None, None, None], [None, None, None]],
 'distances': [[0.00, 0.25, 0.26], [0.00, 0.25, 0.28]]}
使用 OpenAI API 的 Embeddings 入门

添加元数据

import csv 

ids = []
metadatas = []

with open('netflix_titles.csv') as csvfile:
  reader = csv.DictReader(csvfile)
  for i, row in enumerate(reader):
    ids.append(row['show_id'])
    metadatas.append({
      "type":row['type'],
      "release_year": int(row['release_year'])
    })

 

  • 为元数据创建字典列表
  • 创建 ID 列表,将其添加到现有条目
使用 OpenAI API 的 Embeddings 入门

添加与查询元数据

 

collection.update(ids=ids, metadatas=metadatas)
result = collection.query(
    query_texts=reference_texts, 
    n_results=3,
    where={ 
        "type": "Movie"
    }
)
使用 OpenAI API 的 Embeddings 入门

Where 运算符

where={
  "type": "Movie"
}

等同于

where={
  "type": {
    "$eq": "Movie"
  }
}

运算符列表:

  • $eq - 等于(string, int, float)
  • $ne - 不等于(string, int, float)
  • $gt - 大于(int, float)
  • $gte - 大于等于(int, float)
  • $lt - 小于(int, float)
  • $lte - 小于等于(int, float)
使用 OpenAI API 的 Embeddings 入门

多条件 where 筛选

where={
    "$and": [
        {"type": 
            {"$eq": "Movie"}
        },
        {"release_year": 
             {"$gt": 2020}
        }
    ]
}

 

  • $or:基于至少一个条件筛选
使用 OpenAI API 的 Embeddings 入门
Title: A Classic Horror Story (Movie) [...]
===
Title: Nightbooks (Movie) [...]
===
Title: Irul (Movie) [...]
===
Title: Intrusion (Movie) [...]
===
Title: Things Heard & Seen (Movie) [...]
===
Title: A StoryBots Space Adventure (Movie) [...]
使用 OpenAI API 的 Embeddings 入门

开始练习吧!

使用 OpenAI API 的 Embeddings 入门

Preparing Video For Download...