Add hybrid-search module: vector, tsvector and BM25 fused with Reciprocal Rank Fusion in Java and SQL over one PostgreSQL table; quality by query type, held-out k check, plans and latency at 50k rows
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_0146opDKBYtADXvkc39zdiyw
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Okapi BM25 over the passages, held in memory. PostgreSQL's ts_rank and ts_rank_cd are not BM25: they have no
|
||||
* inverse document frequency, so a word found in every passage counts as much as a word found in one. This
|
||||
* class exists to put a real BM25 next to them. Tokens are lower-case runs of letters and digits that may
|
||||
* contain dots, underscores and hyphens, so "E-4116" and "orbit.retry.backoff_ms" each stay one token.
|
||||
*/
|
||||
public final class Bm25 {
|
||||
|
||||
private static final Pattern TOKEN = Pattern.compile("[a-z0-9]+(?:[._-][a-z0-9]+)*");
|
||||
private static final Set<String> STOP = Set.of("a", "an", "the", "of", "to", "in", "is", "are", "and", "or", "for", "on", "at", "be", "by",
|
||||
"do", "does", "how", "what", "why", "can", "it", "its", "we", "our", "i", "my", "me", "with", "was", "this", "that", "from", "as",
|
||||
"have", "has", "when", "which", "if", "so", "not", "no", "am");
|
||||
|
||||
private final double k1;
|
||||
private final double b;
|
||||
private final List<String> ids = new ArrayList<>();
|
||||
private final List<Map<String, Integer>> termFrequencies = new ArrayList<>();
|
||||
private final List<Integer> lengths = new ArrayList<>();
|
||||
private final Map<String, Integer> documentFrequency = new HashMap<>();
|
||||
private final double averageLength;
|
||||
|
||||
public Bm25(List<KnowledgeBase.Passage> passages, double k1, double b) {
|
||||
this.k1 = k1;
|
||||
this.b = b;
|
||||
long total = 0;
|
||||
for (KnowledgeBase.Passage p : passages) {
|
||||
List<String> tokens = tokens(p.text());
|
||||
Map<String, Integer> tf = new LinkedHashMap<>();
|
||||
tokens.forEach(t -> tf.merge(t, 1, Integer::sum));
|
||||
ids.add(p.pid());
|
||||
termFrequencies.add(tf);
|
||||
lengths.add(tokens.size());
|
||||
total += tokens.size();
|
||||
tf.keySet().forEach(t -> documentFrequency.merge(t, 1, Integer::sum));
|
||||
}
|
||||
this.averageLength = (double) total / passages.size();
|
||||
}
|
||||
|
||||
public List<String> search(String query, int n) {
|
||||
List<String> terms = tokens(query);
|
||||
List<double[]> scored = new ArrayList<>();
|
||||
for (int d = 0; d < ids.size(); d++) {
|
||||
double score = 0;
|
||||
for (String term : terms) {
|
||||
Integer f = termFrequencies.get(d).get(term);
|
||||
if (f == null) {
|
||||
continue;
|
||||
}
|
||||
int df = documentFrequency.get(term);
|
||||
double idf = Math.log(1 + (ids.size() - df + 0.5) / (df + 0.5));
|
||||
score += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * lengths.get(d) / averageLength));
|
||||
}
|
||||
if (score > 0) {
|
||||
scored.add(new double[] {d, score});
|
||||
}
|
||||
}
|
||||
scored.sort((x, y) -> Double.compare(y[1], x[1]));
|
||||
return scored.stream().limit(n).map(s -> ids.get((int) s[0])).toList();
|
||||
}
|
||||
|
||||
static List<String> tokens(String text) {
|
||||
List<String> out = new ArrayList<>();
|
||||
Matcher m = TOKEN.matcher(text.toLowerCase(Locale.ROOT));
|
||||
while (m.find()) {
|
||||
String t = m.group();
|
||||
if (STOP.contains(t)) {
|
||||
continue;
|
||||
}
|
||||
out.add(t.length() > 3 && t.endsWith("s") && !t.contains("-") && !t.contains(".") ? t.substring(0, t.length() - 1) : t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.rag.Query;
|
||||
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
|
||||
|
||||
/**
|
||||
* Spring AI's extension point for "where do the passages come from": give it to RetrievalAugmentationAdvisor
|
||||
* and every question is answered from the fused ranking instead of from the vector store alone.
|
||||
*/
|
||||
public class HybridDocumentRetriever implements DocumentRetriever {
|
||||
|
||||
private final HybridSearch search;
|
||||
private final int topK;
|
||||
private final int candidates;
|
||||
private final int k;
|
||||
|
||||
public HybridDocumentRetriever(HybridSearch search, int topK, int candidates, int k) {
|
||||
this.search = search;
|
||||
this.topK = topK;
|
||||
this.candidates = candidates;
|
||||
this.k = k;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Document> retrieve(Query query) {
|
||||
return search.hybrid(query.text(), topK, candidates, k).stream()
|
||||
.map(f -> Document.builder().text(f.content()).score(f.score())
|
||||
.metadata(Map.of("pid", f.pid(), "vector_rank", f.vectorRank(), "keyword_rank", f.keywordRank())).build())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.embedding.EmbeddingModel;
|
||||
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
|
||||
/**
|
||||
* Keyword search, vector search and their fusion over one PostgreSQL table.
|
||||
*
|
||||
* <p>The table is the one Spring AI's PgVectorStore creates (id, content, metadata, embedding). The only thing
|
||||
* added by hand is a generated tsvector column over {@code content} and a GIN index on it, so a passage is
|
||||
* stored once and searched two ways.
|
||||
*/
|
||||
public class HybridSearch {
|
||||
|
||||
public record Hit(String pid, String content) {
|
||||
}
|
||||
|
||||
/** One fused result: the passage, its RRF score and the rank it had in each list (0 when absent). */
|
||||
public record Fused(String pid, String content, double score, int vectorRank, int keywordRank) {
|
||||
}
|
||||
|
||||
/** The English tsquery of a question with its AND turned into OR, so one rare word is enough to match. */
|
||||
static final String OR_QUERY = "replace(plainto_tsquery('english', :text)::text, ' & ', ' | ')::tsquery";
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final NamedParameterJdbcTemplate named;
|
||||
private final EmbeddingModel model;
|
||||
private final String table;
|
||||
|
||||
public HybridSearch(JdbcTemplate jdbc, EmbeddingModel model, String table) {
|
||||
this.jdbc = jdbc;
|
||||
this.named = new NamedParameterJdbcTemplate(jdbc);
|
||||
this.model = model;
|
||||
this.table = table;
|
||||
}
|
||||
|
||||
/** Creates the PgVectorStore table, loads the passages through it, then adds the tsvector column and its index. */
|
||||
public static HybridSearch load(JdbcTemplate jdbc, EmbeddingModel model, String table, List<KnowledgeBase.Passage> passages) throws Exception {
|
||||
PgVectorStore store = PgVectorStore.builder(jdbc, model).vectorTableName(table).dimensions(384)
|
||||
.removeExistingVectorStoreTable(true).initializeSchema(true).build();
|
||||
store.afterPropertiesSet();
|
||||
List<Document> docs = new ArrayList<>();
|
||||
for (KnowledgeBase.Passage p : passages) {
|
||||
docs.add(Document.builder().id(UUID.nameUUIDFromBytes(p.pid().getBytes(StandardCharsets.UTF_8)).toString())
|
||||
.text(p.text()).metadata(Map.of("pid", p.pid(), "kind", p.kind())).build());
|
||||
}
|
||||
store.add(docs);
|
||||
addKeywordIndex(jdbc, table);
|
||||
return new HybridSearch(jdbc, model, table);
|
||||
}
|
||||
|
||||
public static void addKeywordIndex(JdbcTemplate jdbc, String table) {
|
||||
jdbc.execute("alter table " + table + " add column if not exists tsv tsvector generated always as (to_tsvector('english', content)) stored");
|
||||
jdbc.execute("create index if not exists " + table + "_tsv_idx on " + table + " using gin (tsv)");
|
||||
jdbc.execute("analyze " + table);
|
||||
}
|
||||
|
||||
public List<Hit> vector(String text, int n) {
|
||||
return vectorByLiteral(literal(model.embed(text)), n);
|
||||
}
|
||||
|
||||
/** The same query with the question already embedded, so a timing can leave the embedding model out. */
|
||||
public List<Hit> vectorByLiteral(String vectorLiteral, int n) {
|
||||
return named.query("select metadata->>'pid' as pid, content from " + table
|
||||
+ " order by embedding <=> cast(:vec as vector) limit :n",
|
||||
new MapSqlParameterSource("vec", vectorLiteral).addValue("n", n),
|
||||
(rs, i) -> new Hit(rs.getString("pid"), rs.getString("content")));
|
||||
}
|
||||
|
||||
public List<Hit> keyword(String text, int n) {
|
||||
return named.query("with q as (select " + OR_QUERY + " as query) select d.metadata->>'pid' as pid, d.content, "
|
||||
+ "ts_rank_cd(d.tsv, q.query) as score from " + table + " d, q where d.tsv @@ q.query "
|
||||
+ "order by score desc, d.id limit :n",
|
||||
new MapSqlParameterSource("text", text).addValue("n", n),
|
||||
(rs, i) -> new Hit(rs.getString("pid"), rs.getString("content")));
|
||||
}
|
||||
|
||||
/** Two queries, fused in Java: this is what a DocumentRetriever does. */
|
||||
public List<Fused> hybrid(String text, int n, int candidates, int k) {
|
||||
List<Hit> vector = vector(text, candidates);
|
||||
List<Hit> keyword = keyword(text, candidates);
|
||||
return fuse(vector, keyword, n, k);
|
||||
}
|
||||
|
||||
public static List<Fused> fuse(List<Hit> vector, List<Hit> keyword, int n, int k) {
|
||||
List<String> v = vector.stream().map(Hit::pid).toList();
|
||||
List<String> w = keyword.stream().map(Hit::pid).toList();
|
||||
Map<String, String> content = new LinkedHashMap<>();
|
||||
vector.forEach(h -> content.putIfAbsent(h.pid(), h.content()));
|
||||
keyword.forEach(h -> content.putIfAbsent(h.pid(), h.content()));
|
||||
return ReciprocalRankFusion.fuse(List.of(v, w), k).stream().limit(n)
|
||||
.map(f -> new Fused(f.id(), content.get(f.id()), f.score(), v.indexOf(f.id()) + 1, w.indexOf(f.id()) + 1))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* The same fusion written as one SQL statement. Equal scores are common in RRF (rank 1 in one list only
|
||||
* equals rank 1 in the other), so the tie-break is spelled out to match fuse(): vector-list order first,
|
||||
* then keyword-only items in keyword order.
|
||||
*/
|
||||
public List<String> hybridSql(String text, int n, int candidates, int k) {
|
||||
return hybridSqlByLiteral(text, literal(model.embed(text)), n, candidates, k);
|
||||
}
|
||||
|
||||
public List<String> hybridSqlByLiteral(String text, String vectorLiteral, int n, int candidates, int k) {
|
||||
return named.query("""
|
||||
with q as (select %s as tsq, cast(:vec as vector) as v),
|
||||
sem as (select id, row_number() over (order by dist) as r from
|
||||
(select d.id, d.embedding <=> q.v as dist from %s d, q order by dist limit :cand) s),
|
||||
kw as (select id, row_number() over (order by score desc, id) as r from
|
||||
(select d.id, ts_rank_cd(d.tsv, q.tsq) as score from %s d, q where d.tsv @@ q.tsq
|
||||
order by score desc, d.id limit :cand) s)
|
||||
select d.metadata->>'pid' as pid,
|
||||
coalesce(1.0 / (:k + sem.r), 0) + coalesce(1.0 / (:k + kw.r), 0) as score
|
||||
from sem full outer join kw on sem.id = kw.id
|
||||
join %s d on d.id = coalesce(sem.id, kw.id)
|
||||
order by score desc, sem.r nulls last, kw.r nulls last
|
||||
limit :n
|
||||
""".formatted(OR_QUERY, table, table, table),
|
||||
new MapSqlParameterSource("text", text).addValue("vec", vectorLiteral)
|
||||
.addValue("cand", candidates).addValue("k", k).addValue("n", n),
|
||||
(rs, i) -> rs.getString("pid"));
|
||||
}
|
||||
|
||||
public JdbcTemplate jdbc() {
|
||||
return jdbc;
|
||||
}
|
||||
|
||||
public String table() {
|
||||
return table;
|
||||
}
|
||||
|
||||
public static String literal(float[] v) {
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
for (int i = 0; i < v.length; i++) {
|
||||
if (i > 0) {
|
||||
sb.append(',');
|
||||
}
|
||||
sb.append(v[i]);
|
||||
}
|
||||
return sb.append(']').toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A made-up support knowledge base for a payments API called Orbit: 94 passages and 60 labelled queries.
|
||||
* Every query has exactly one passage that answers it, named by {@code pid}.
|
||||
*
|
||||
* <p>The passages come in three kinds, because the three kinds are where the two search methods differ:
|
||||
* 40 error codes whose texts all look alike and differ in the identifier and one fact, 24 hardware and
|
||||
* configuration identifiers (SKUs and setting names), and 30 how-to guides written in plain language.
|
||||
* The corpus is synthetic and small. It shows how the methods behave, not how any of them scales.
|
||||
*/
|
||||
public final class KnowledgeBase {
|
||||
|
||||
public record Passage(String pid, String kind, String text) {
|
||||
}
|
||||
|
||||
public record Query(String text, String pid, String category) {
|
||||
}
|
||||
|
||||
public static final String EXACT_CODE = "exact error code";
|
||||
public static final String EXACT_ID = "exact SKU or setting";
|
||||
public static final String PARAPHRASE = "paraphrase";
|
||||
public static final String MIXED = "code plus words";
|
||||
|
||||
public static final List<Passage> PASSAGES = new ArrayList<>();
|
||||
public static final List<Query> QUERIES = new ArrayList<>();
|
||||
|
||||
private static void error(String code, String title, String body) {
|
||||
PASSAGES.add(new Passage(code, "error", "Error " + code + " - " + title + ". " + body));
|
||||
}
|
||||
|
||||
private static void item(String id, String kind, String text) {
|
||||
PASSAGES.add(new Passage(id, kind, text));
|
||||
}
|
||||
|
||||
private static void guide(String id, String title, String body) {
|
||||
PASSAGES.add(new Passage(id, "guide", title + ". " + body));
|
||||
}
|
||||
|
||||
private static void q(String category, String pid, String text) {
|
||||
QUERIES.add(new Query(text, pid, category));
|
||||
}
|
||||
|
||||
static {
|
||||
// ---- 40 error codes -------------------------------------------------------------------------------
|
||||
error("E-4101", "Missing idempotency key", "Requests that create a charge must send an Idempotency-Key header. A request without one is rejected before any money moves. Generate a fresh UUID for each logical payment attempt.");
|
||||
error("E-4102", "Idempotency key reused with a different body", "The same Idempotency-Key arrived with a different request body. Orbit replays the stored response only when the body is identical, and otherwise refuses the call.");
|
||||
error("E-4103", "Unsupported currency", "The currency code is not enabled for this merchant account. Enable it in the dashboard under Settings, or convert the amount before calling the API.");
|
||||
error("E-4104", "Amount below minimum", "The charge is smaller than the minimum for its currency, which is fifty cents for dollars. Orbit does not process smaller amounts.");
|
||||
error("E-4105", "Amount above limit", "The amount is higher than the per-transaction ceiling set for the merchant. Ask support to raise the ceiling or split the order into several charges.");
|
||||
error("E-4106", "Webhook signature mismatch", "The signature header on a webhook did not match the value computed with the endpoint secret. Verify against the raw request body, not the parsed JSON, because re-serialising changes the bytes.");
|
||||
error("E-4107", "Webhook timestamp too old", "The timestamp inside the webhook signature is more than five minutes in the past. This guards against replays. Check for clock drift on the receiving server.");
|
||||
error("E-4108", "Card expired", "The expiry date on the card has passed. Ask the customer for a different card or for the new expiry date before trying again.");
|
||||
error("E-4109", "Card number invalid", "The card number fails the Luhn checksum, which usually means a typing mistake. Orbit rejects it locally without contacting the issuer.");
|
||||
error("E-4110", "Strong customer authentication required", "The issuer demands a 3-D Secure challenge before it will approve the payment. Redirect the customer to the authentication page and confirm the payment afterwards.");
|
||||
error("E-4111", "Authentication challenge failed", "The customer abandoned or failed the 3-D Secure challenge. The payment cannot be completed with this card; offer another payment method.");
|
||||
error("E-4112", "Issuer declined without a reason", "The card issuer returned a generic do-not-honor response. Orbit cannot see the real cause. The customer should call their bank or use a different card.");
|
||||
error("E-4113", "Insufficient funds", "The account behind the card does not have enough available balance for the amount. A later retry may succeed once the customer tops up.");
|
||||
error("E-4114", "Refund larger than the captured amount", "The refund requested is more than what was captured on the charge, after earlier partial refunds are taken off. Lower the refund amount.");
|
||||
error("E-4115", "Refund window closed", "Refunds to cards are possible for 180 days after capture. After that the money must be returned by bank transfer outside Orbit.");
|
||||
error("E-4116", "Charge already captured", "A capture was attempted on a charge that has already been captured in full. Fetch the charge first and check its status instead of capturing blindly.");
|
||||
error("E-4117", "Authorization expired", "An authorization that is not captured within seven days lapses and the hold is released. Create a new authorization if the goods ship later.");
|
||||
error("E-4118", "Payout account not verified", "Payouts are blocked because the bank account has not passed verification. Confirm the two micro-deposits shown in the dashboard to unlock transfers.");
|
||||
error("E-4119", "Payout below threshold", "The available balance is under ten units of currency, so the scheduled payout was skipped. It will be included in the next run once the balance grows.");
|
||||
error("E-4120", "Dispute evidence deadline passed", "Evidence for a chargeback must be submitted before the deadline printed on the dispute. After it passes the dispute is lost automatically.");
|
||||
error("E-4121", "Customer not found", "No customer exists with the identifier supplied. It may belong to the other mode, since test and live objects are kept apart.");
|
||||
error("E-4122", "Payment method not attached", "The payment method is not attached to this customer. Attach it first, or pass it directly on a one-off charge.");
|
||||
error("E-4123", "Duplicate customer email", "A customer with this email address already exists and the account is configured to enforce unique emails. Reuse the existing customer.");
|
||||
error("E-4124", "Plan archived", "The subscription plan was archived and cannot be chosen by new subscribers. Existing subscribers keep it until they cancel.");
|
||||
error("E-4125", "Proration not allowed during trial", "Prorated billing cannot be applied while the subscription is still in its free trial. Change the plan at the end of the trial instead.");
|
||||
error("E-4126", "Coupon expired", "The coupon passed its redemption end date. Create a new coupon or extend the validity in the dashboard.");
|
||||
error("E-4127", "Coupon already redeemed", "This single-use coupon was already redeemed by another order. Issue a fresh code for each customer.");
|
||||
error("E-4128", "Tax identifier invalid", "The tax registration number does not match the format for its country. Check the prefix and the number of digits.");
|
||||
error("E-4129", "API key lacks permission", "The key in use does not carry the scope needed for this endpoint. Create a restricted key that includes it.");
|
||||
error("E-4130", "API key revoked", "The secret key was revoked, either by a team member or automatically after it was found in a public repository. Issue a new key and rotate it in your deployment.");
|
||||
error("E-4131", "Rate limit exceeded", "More than one hundred requests per second arrived on this key. Back off with jitter and respect the Retry-After header.");
|
||||
error("E-4132", "Request body too large", "The request payload is bigger than one megabyte. Upload large files through the file endpoint and reference them by identifier.");
|
||||
error("E-4133", "Unknown parameter", "The request contains a field that this API version does not define. Remove it or pin a newer API version.");
|
||||
error("E-4134", "Metadata key too long", "A metadata key is longer than forty characters. Shorten the key names.");
|
||||
error("E-4135", "Too many metadata keys", "An object may carry at most fifty metadata keys. Store bulky data in your own database and keep only a reference.");
|
||||
error("E-4136", "Test card used in live mode", "One of the published test card numbers was used with a live key. Switch to the test key, or use a real card.");
|
||||
error("E-4137", "Live card used in test mode", "A real card number was sent with a test key. Orbit never charges real cards in test mode, so use a test card.");
|
||||
error("E-4138", "Terminal offline", "The card terminal has not sent a heartbeat and cannot take payments. Check its network connection and power.");
|
||||
error("E-4139", "Terminal firmware outdated", "The terminal runs firmware older than the minimum supported release. Connect it to power and wifi so it can update overnight.");
|
||||
error("E-4140", "Receipt email bounced", "The receipt could not be delivered because the address rejected it. The payment itself is unaffected.");
|
||||
|
||||
// ---- 12 hardware, plan and support identifiers ------------------------------------------------------
|
||||
item("OP-TERM-5520", "sku", "OP-TERM-5520 countertop card terminal with a 4G fallback modem. Accepts chip, tap and swipe, and keeps working for up to eight hours of sales if the shop network drops.");
|
||||
item("OP-TERM-5530", "sku", "OP-TERM-5530 handheld card terminal with a built-in receipt printer and a six hour battery. Intended for table service in restaurants.");
|
||||
item("OP-TERM-6100", "sku", "OP-TERM-6100 unattended card reader for kiosks and vending machines. Vandal-resistant housing, no display, powered over the serial port.");
|
||||
item("OP-DOCK-210", "sku", "OP-DOCK-210 charging dock for the handheld terminals. Holds a single unit and charges it to full in about ninety minutes.");
|
||||
item("OP-PRNT-77", "sku", "OP-PRNT-77 thermal paper rolls, 58 millimetres wide, sold in boxes of fifty. Fits the handheld terminal.");
|
||||
item("OP-SIM-EU1", "sku", "OP-SIM-EU1 data SIM for terminals used across the European Union, with roaming included and no monthly minimum.");
|
||||
item("OP-STND-45", "sku", "OP-STND-45 adjustable stand for countertop terminals. Tilts from zero to forty-five degrees and has a lockable base.");
|
||||
item("OP-PLAN-STD", "plan", "OP-PLAN-STD standard pricing plan: 2.4 percent plus twenty cents per successful card charge, no monthly fee, payouts every two business days.");
|
||||
item("OP-PLAN-PLUS", "plan", "OP-PLAN-PLUS pricing plan for growing merchants: 1.9 percent plus twenty cents per charge, a monthly fee, and next business day payouts.");
|
||||
item("OP-PLAN-ENT", "plan", "OP-PLAN-ENT enterprise plan with negotiated rates, a named account manager and a custom payout calendar.");
|
||||
item("OP-SUP-GOLD", "support", "OP-SUP-GOLD gold support tier: a human answers within one hour at any time of day, with a phone line for outages.");
|
||||
item("OP-SUP-SILV", "support", "OP-SUP-SILV silver support tier: email answers within one business day, no phone line.");
|
||||
|
||||
// ---- 12 configuration settings ---------------------------------------------------------------------
|
||||
item("orbit.retry.max_attempts", "setting", "Setting orbit.retry.max_attempts is the number of times the client library repeats a failed request before giving up. The default is 5.");
|
||||
item("orbit.retry.backoff_ms", "setting", "Setting orbit.retry.backoff_ms is the initial wait between retries in milliseconds. It doubles after each attempt. The default is 250.");
|
||||
item("orbit.webhook.tolerance_seconds", "setting", "Setting orbit.webhook.tolerance_seconds is how old a webhook signature timestamp may be before verification fails. The default is 300.");
|
||||
item("orbit.http.timeout_ms", "setting", "Setting orbit.http.timeout_ms is the total time the client waits for a response. The default is 30000.");
|
||||
item("orbit.capture.mode", "setting", "Setting orbit.capture.mode chooses between automatic capture at authorization and manual capture later. The default is automatic.");
|
||||
item("orbit.idempotency.ttl_hours", "setting", "Setting orbit.idempotency.ttl_hours is how long Orbit remembers an idempotency key and replays its response. The default is 24.");
|
||||
item("orbit.radar.threshold", "setting", "Setting orbit.radar.threshold is the risk score from 0 to 100 above which a payment is blocked. The default is 75.");
|
||||
item("orbit.payout.schedule", "setting", "Setting orbit.payout.schedule picks daily, weekly or monthly payouts. The default is daily.");
|
||||
item("orbit.receipts.locale", "setting", "Setting orbit.receipts.locale is the language of emailed receipts. The default follows the customer's browser.");
|
||||
item("orbit.terminal.heartbeat_seconds", "setting", "Setting orbit.terminal.heartbeat_seconds is how often a terminal reports in. After three missed beats it is shown as offline. The default is 60.");
|
||||
item("orbit.log.level", "setting", "Setting orbit.log.level controls how much the client library writes to its log. The default is warn.");
|
||||
item("orbit.cache.customer_ttl_s", "setting", "Setting orbit.cache.customer_ttl_s is how long customer objects are cached inside the client. The default is 120.");
|
||||
|
||||
// ---- 30 guides in plain language --------------------------------------------------------------------
|
||||
guide("G-01", "Recovering failed subscription renewals", "When a renewal charge fails, Orbit runs a dunning schedule: it retries after one, three and five days, then marks the subscription past due and emails the customer a link to update their card.");
|
||||
guide("G-02", "Paying several sellers from one order", "A marketplace can divide the proceeds of a single charge between sellers using connected accounts and transfers. Each seller is paid out on their own schedule and the platform keeps its fee.");
|
||||
guide("G-03", "Authorise now, capture on dispatch", "Place a hold on the card when the order is made and capture it when the goods ship. The hold guarantees the funds for seven days and can be released without any fee.");
|
||||
guide("G-04", "Responding to a chargeback", "When a cardholder disputes a payment their bank takes the money back at once. Gather proof of delivery and customer communication and submit it through the dispute page before the deadline.");
|
||||
guide("G-05", "Trying the integration without real money", "Test mode mirrors live mode with separate keys and published card numbers that simulate approvals, declines and challenges. Nothing in test mode moves real funds.");
|
||||
guide("G-06", "Remembering a shopper's card", "Attach a payment method to a customer object after the first purchase. Later orders can then reuse it, and the shopper never types the number again.");
|
||||
guide("G-07", "Taking payment from people without cards", "Orbit supports bank redirects, wallets and instant bank transfers. Enable the methods in the dashboard and they appear in the checkout automatically for eligible countries.");
|
||||
guide("G-08", "When refunded money arrives", "A refund is sent to the bank immediately but most issuers need five to ten business days to show it on the customer's statement.");
|
||||
guide("G-09", "What shows on the cardholder's statement", "The statement descriptor is the short text a cardholder sees next to the charge. Choose one customers will recognise to avoid unnecessary disputes.");
|
||||
guide("G-10", "Blocking suspicious orders", "Radar scores every payment for fraud risk using signals across the network. Rules let you block, review or allow payments based on the score, the country or the card type.");
|
||||
guide("G-11", "When funds reach your bank account", "Settled funds are paid to your bank on a rolling schedule. New accounts wait longer for the first payout while Orbit builds a history.");
|
||||
guide("G-12", "If your server is unreachable", "When your endpoint does not answer, Orbit redelivers the event with increasing gaps for up to three days. You can also list missed events through the events endpoint and replay them.");
|
||||
guide("G-13", "Charging in one currency and settling in another", "Present prices in the shopper's currency and Orbit converts to your settlement currency at the daily rate, adding a small conversion fee to the payout.");
|
||||
guide("G-14", "Adding sales tax to bills", "Orbit Tax calculates the rate from the customer's address and the product category, adds it to the invoice and keeps the reports you need for filing.");
|
||||
guide("G-15", "Giving new customers a free period", "Set a trial length on the plan. The customer is not charged until the trial ends, and a reminder is emailed three days before the first payment.");
|
||||
guide("G-16", "Putting a subscription on hold", "Pausing stops invoices while keeping the customer and their payment method. Billing resumes on the date you choose and the cycle is shifted accordingly.");
|
||||
guide("G-17", "Handing transactions to the accountants", "Export every transaction, fee and payout for a date range as a spreadsheet. The report reconciles to the bank deposits line by line.");
|
||||
guide("G-18", "Restricting what a team member can see", "Dashboard roles control who can view balances, issue refunds or read customer details. Give support staff the limited role so they cannot see payout accounts.");
|
||||
guide("G-19", "Keeping European data in Europe", "Choose the EU region when you create the account and customer and card data are stored and processed only in European data centres.");
|
||||
guide("G-20", "Staying out of card data rules", "Hosted fields and the checkout page collect card numbers on Orbit's servers, so they never touch yours and your compliance questionnaire stays short.");
|
||||
guide("G-21", "Accepting taps on a phone", "The mobile SDK turns a supported phone into a contactless reader, with no extra hardware, for cards and wallets.");
|
||||
guide("G-22", "Customising the emailed receipt", "Add your logo, brand colour and a footer message to receipts under Settings. Receipts are sent automatically after each successful payment.");
|
||||
guide("G-23", "Resending a request that timed out", "If a call times out you cannot know whether it succeeded. Send it again with the same idempotency key and Orbit returns the original result instead of creating a second charge.");
|
||||
guide("G-24", "Taking part of an authorised amount", "You may capture less than was authorised, for example when one item of an order is out of stock. The rest of the hold is released straight away.");
|
||||
guide("G-25", "Letting customers add a tip", "Collect a gratuity on the terminal after the amount is shown. The tip is added to the same charge and reported separately.");
|
||||
guide("G-26", "Showing local prices", "Define a price per currency on each product so shoppers see round local amounts instead of converted ones.");
|
||||
guide("G-27", "Clearing out sandbox data", "Reset the test environment from the developer settings page to delete test customers, charges and subscriptions and start clean.");
|
||||
guide("G-28", "Seeing who changed what", "The audit log records every dashboard action with the person, time and address, and can be exported for your security team.");
|
||||
guide("G-29", "Signing in with your company directory", "Single sign-on lets the team log in to the dashboard through your identity provider, and access is removed automatically when someone leaves.");
|
||||
guide("G-30", "Checking whether Orbit is having problems", "The status page lists current incidents and past outages per region, and you can subscribe to updates by email or webhook.");
|
||||
|
||||
// ---- 60 queries --------------------------------------------------------------------------------------
|
||||
// 12 where the only useful words are an error code
|
||||
q(EXACT_CODE, "E-4106", "What does error E-4106 mean?");
|
||||
q(EXACT_CODE, "E-4116", "Why am I getting E-4116?");
|
||||
q(EXACT_CODE, "E-4118", "We see E-4118 in the logs, what should we do?");
|
||||
q(EXACT_CODE, "E-4120", "Explain E-4120");
|
||||
q(EXACT_CODE, "E-4122", "Support told me to look up E-4122");
|
||||
q(EXACT_CODE, "E-4126", "What is E-4126?");
|
||||
q(EXACT_CODE, "E-4129", "How do I fix E-4129?");
|
||||
q(EXACT_CODE, "E-4131", "Our service started returning E-4131 this morning");
|
||||
q(EXACT_CODE, "E-4133", "Meaning of E-4133");
|
||||
q(EXACT_CODE, "E-4135", "Is E-4135 our fault?");
|
||||
q(EXACT_CODE, "E-4138", "What causes E-4138 on the shop floor?");
|
||||
q(EXACT_CODE, "E-4140", "Customer reports E-4140, is the money safe?");
|
||||
|
||||
// 12 where the identifier is a SKU, plan or setting name
|
||||
q(EXACT_ID, "OP-TERM-5520", "Does OP-TERM-5520 work when the internet is down?");
|
||||
q(EXACT_ID, "OP-TERM-5530", "Tell me about OP-TERM-5530");
|
||||
q(EXACT_ID, "OP-TERM-6100", "Can OP-TERM-6100 be used in a vending machine?");
|
||||
q(EXACT_ID, "OP-DOCK-210", "How long does OP-DOCK-210 take to charge a unit?");
|
||||
q(EXACT_ID, "OP-PRNT-77", "What size is OP-PRNT-77?");
|
||||
q(EXACT_ID, "OP-PLAN-PLUS", "What are the rates on OP-PLAN-PLUS?");
|
||||
q(EXACT_ID, "OP-SUP-GOLD", "Response time for OP-SUP-GOLD");
|
||||
q(EXACT_ID, "orbit.retry.backoff_ms", "What is the default for orbit.retry.backoff_ms?");
|
||||
q(EXACT_ID, "orbit.radar.threshold", "Value of orbit.radar.threshold");
|
||||
q(EXACT_ID, "orbit.idempotency.ttl_hours", "What does orbit.idempotency.ttl_hours do?");
|
||||
q(EXACT_ID, "orbit.terminal.heartbeat_seconds", "Default of orbit.terminal.heartbeat_seconds");
|
||||
q(EXACT_ID, "orbit.cache.customer_ttl_s", "Explain orbit.cache.customer_ttl_s");
|
||||
|
||||
// 24 plain-language questions written without the passage's own distinctive words
|
||||
q(PARAPHRASE, "G-01", "What happens when a customer's monthly payment does not go through?");
|
||||
q(PARAPHRASE, "G-02", "How can an online mall split one shopper's purchase among several vendors?");
|
||||
q(PARAPHRASE, "G-03", "Can I reserve money on a card and only take it once the parcel leaves?");
|
||||
q(PARAPHRASE, "G-04", "A buyer told their bank they never got the item. What now?");
|
||||
q(PARAPHRASE, "G-05", "How do I experiment safely before launching?");
|
||||
q(PARAPHRASE, "G-06", "Store a shopper's card so they do not re-enter it next time");
|
||||
q(PARAPHRASE, "G-07", "Accept money from people who do not own a credit card");
|
||||
q(PARAPHRASE, "G-08", "How long until the buyer sees their money back?");
|
||||
q(PARAPHRASE, "G-09", "Which words appear on the customer's bank statement?");
|
||||
q(PARAPHRASE, "G-10", "Stop dodgy purchases automatically");
|
||||
q(PARAPHRASE, "G-11", "When will the money land in our account?");
|
||||
q(PARAPHRASE, "G-12", "What if our website is down when you send us news?");
|
||||
q(PARAPHRASE, "G-13", "Show prices in euros but receive dollars");
|
||||
q(PARAPHRASE, "G-14", "Include VAT on our bills without doing sums");
|
||||
q(PARAPHRASE, "G-15", "Let new users try the product for two weeks at no cost");
|
||||
q(PARAPHRASE, "G-16", "A client wants to stop being billed for the summer");
|
||||
q(PARAPHRASE, "G-17", "Give our bookkeeper everything that came in last quarter");
|
||||
q(PARAPHRASE, "G-18", "Limit what a helpdesk employee can look at");
|
||||
q(PARAPHRASE, "G-19", "Our lawyers want shopper information to stay on this continent");
|
||||
q(PARAPHRASE, "G-20", "How do we avoid ever handling raw card numbers ourselves?");
|
||||
q(PARAPHRASE, "G-21", "Take contactless payments with just a smartphone");
|
||||
q(PARAPHRASE, "G-23", "Our call hung and we do not know if it worked. Is it safe to send it again?");
|
||||
q(PARAPHRASE, "G-24", "One item in the basket is sold out, can we bill only for the rest?");
|
||||
q(PARAPHRASE, "G-28", "Which colleague altered the settings last Tuesday?");
|
||||
|
||||
// 12 that carry a code and also say what it is about
|
||||
q(MIXED, "E-4106", "E-4106 keeps appearing in our Express webhook handler, is the body being parsed?");
|
||||
q(MIXED, "E-4113", "Customer card gets E-4113 although they swear there is money on it");
|
||||
q(MIXED, "E-4117", "E-4117 on capture, the goods shipped ten days after the order");
|
||||
q(MIXED, "E-4125", "Plan change during trial returns E-4125");
|
||||
q(MIXED, "E-4130", "E-4130 on every call since the key leaked into our repository");
|
||||
q(MIXED, "E-4115", "Cannot refund a purchase from last year, E-4115");
|
||||
q(MIXED, "E-4110", "E-4110 and the customer is asked for a bank challenge");
|
||||
q(MIXED, "E-4127", "Promo code gives E-4127 for the second shopper");
|
||||
q(MIXED, "E-4139", "Terminal says E-4139 and needs an update");
|
||||
q(MIXED, "E-4101", "Getting E-4101 on the charge endpoint, our client does not set the idempotency header");
|
||||
q(MIXED, "E-4131", "E-4131 during the flash sale, too many requests per second");
|
||||
q(MIXED, "E-4119", "Why was our payout skipped, E-4119, the balance was small");
|
||||
}
|
||||
|
||||
private KnowledgeBase() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.ai.document.MetadataMode;
|
||||
import org.springframework.ai.embedding.EmbeddingModel;
|
||||
import org.springframework.ai.transformers.TransformersEmbeddingModel;
|
||||
|
||||
/**
|
||||
* all-MiniLM-L6-v2 (384 dimensions) running inside the JVM through ONNX Runtime. Both model files come from
|
||||
* Hugging Face and are cached under the user's home directory, so the first run downloads about 90 MB and
|
||||
* later runs are offline. No API key is involved, which is what lets anyone repeat the measurements.
|
||||
*/
|
||||
public final class MiniLm {
|
||||
|
||||
private static final String HF = "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/";
|
||||
private static EmbeddingModel shared;
|
||||
|
||||
private MiniLm() {
|
||||
}
|
||||
|
||||
/** The shared instance, which embeds the text of a Document only (MetadataMode.NONE, the constructor default). */
|
||||
public static synchronized EmbeddingModel get() {
|
||||
if (shared == null) {
|
||||
shared = create(MetadataMode.NONE);
|
||||
}
|
||||
return shared;
|
||||
}
|
||||
|
||||
/** A fresh instance whose Document embedding content is built with the given metadata mode. */
|
||||
public static EmbeddingModel create(MetadataMode mode) {
|
||||
try {
|
||||
TransformersEmbeddingModel m = new TransformersEmbeddingModel(mode);
|
||||
m.setTokenizerResource(HF + "tokenizer.json");
|
||||
m.setModelResource(HF + "onnx/model.onnx");
|
||||
m.setResourceCacheDirectory(System.getProperty("user.home") + "/.cache/minilm");
|
||||
m.setTokenizerOptions(Map.of("padding", "true", "truncation", "true", "maxLength", "256"));
|
||||
m.afterPropertiesSet();
|
||||
return m;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.hybridsearch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Reciprocal Rank Fusion: every ranking gives each item {@code weight / (k + rank)} (rank starts at 1) and the
|
||||
* item's fused score is the sum over the rankings it appears in. Only ranks are used, never the scores
|
||||
* the rankings were built from, which is why it can join a cosine similarity and a text rank that live on
|
||||
* different scales without any normalisation. {@code k} (60 in the original paper) flattens the curve: the
|
||||
* larger it is, the less the very top places matter.
|
||||
*/
|
||||
public final class ReciprocalRankFusion {
|
||||
|
||||
public record Fused(String id, double score) {
|
||||
}
|
||||
|
||||
private ReciprocalRankFusion() {
|
||||
}
|
||||
|
||||
public static List<Fused> fuse(List<List<String>> rankings, int k) {
|
||||
double[] ones = new double[rankings.size()];
|
||||
java.util.Arrays.fill(ones, 1.0);
|
||||
return fuse(rankings, ones, k);
|
||||
}
|
||||
|
||||
public static List<Fused> fuse(List<List<String>> rankings, double[] weights, int k) {
|
||||
Map<String, Double> scores = new LinkedHashMap<>();
|
||||
for (int r = 0; r < rankings.size(); r++) {
|
||||
List<String> ranking = rankings.get(r);
|
||||
for (int i = 0; i < ranking.size(); i++) {
|
||||
scores.merge(ranking.get(i), weights[r] / (k + i + 1), Double::sum);
|
||||
}
|
||||
}
|
||||
List<Fused> out = new ArrayList<>();
|
||||
scores.forEach((id, score) -> out.add(new Fused(id, score)));
|
||||
// equal scores keep the order in which the ids first appeared, so the result is deterministic
|
||||
out.sort((a, b) -> Double.compare(b.score(), a.score()));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user