Keyword vs Meaning: Hybrid Search

"reimburse my cash" shares no words with "we refund your money", yet means the same. Combine keyword and meaning scores.

AI · intermediate · 6 min · 15 steps · free

What you'll learn

hybrid_search.py

SAME_MEANING = {'cash': 'money', 'reimburse': 'refund', 'return': 'refund'}

def keyword_score(query, doc):
    return len(set(query.split()) & set(doc.split()))

def meaning_score(query, doc):
    q = {SAME_MEANING.get(w, w) for w in query.split()}
    d = {SAME_MEANING.get(w, w) for w in doc.split()}
    return len(q & d)

doc = 'we refund your money'
query = 'reimburse my cash'
keyword = keyword_score(query, doc)
meaning = meaning_score(query, doc)
hybrid = 0.3 * keyword + 0.7 * meaning
print(keyword, meaning, hybrid)

Step by step

  1. SAME_MEANING is created and points to a new dict: {cash: 'money', reimburse: 'refund', return: 'refund'}.
  2. Python defines the function keyword_score(). Its body does not run yet: it runs each time the function is called.
  3. Python defines the function meaning_score(). Its body does not run yet: it runs each time the function is called.
  4. doc is created with the value 'we refund your money'.
  5. query is created with the value 'reimburse my cash'.
  6. Python calls keyword_score(), with query = 'reimburse my cash' and doc = 'we refund your money'. It gets its own names.
  7. The function returns len(set(query.split()) & set(doc.split())).
  8. Keyword search finds 0 shared words: it would miss this document completely.
  9. Python calls meaning_score(), with query = 'reimburse my cash' and doc = 'we refund your money'. It gets its own names.
  10. "reimburse" became "refund" and "cash" became "money".
  11. d is created and points to a new set: ['money', 'refund', 'we', 'your'].
  12. The function returns len(q & d).
  13. By meaning, two words match.
  14. 0.3 × 0 + 0.7 × 2 = 1.4: the blended score.
  15. It prints 0 2 1.4.

Common mistakes

Best practices

Key takeaways

Check yourself

Best for finding "error E-4012"?

Answer: Keyword search. Exact codes have no "meaning" to embed.

Best for "I want my money back"?

Answer: Meaning search

·

More in Retrieval