多重查詢與篩選

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

基於多個資料點的電影推薦

 

  • Terrifier(id:'s8170'
  • Strawberry Shortcake: Berry Bitty Adventures(id:'s8103'
Introduction to Embeddings with the OpenAI API

多筆查詢文字

reference_ids = ['s8170', 's8103']


reference_texts = collection.get(ids=reference_ids)["documents"]
result = collection.query( query_texts=reference_texts, n_results=3 )
Introduction to Embeddings with the OpenAI API

多筆查詢文字的結果

{'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]]}
Introduction to Embeddings with the OpenAI API

加入中介資料

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'])
    })

 

  • 建立 metadatas 的字典清單
  • 建立要加入到現有項目的 ID 清單
Introduction to Embeddings with the OpenAI API

加入並查詢中介資料

 

collection.update(ids=ids, metadatas=metadatas)
result = collection.query(
    query_texts=reference_texts, 
    n_results=3,
    where={ 
        "type": "Movie"
    }
)
Introduction to Embeddings with the OpenAI API

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)
Introduction to Embeddings with the OpenAI API

多重 where 篩選

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

 

  • $or:符合「至少」一個條件即通過
Introduction to Embeddings with the OpenAI API
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) [...]
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...