-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweaviate.rb
More file actions
133 lines (107 loc) · 2.69 KB
/
weaviate.rb
File metadata and controls
133 lines (107 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# frozen_string_literal: true
require 'faraday'
# Simple Weaviate client wrapper using Faraday
class WeaviateClient
attr_reader :url, :conn
def initialize(url)
@url = url
@conn = Faraday.new(url: url) do |f|
f.request :json
f.response :json
f.adapter Faraday.default_adapter
end
end
def schema
SchemaAPI.new(self)
end
def objects
ObjectsAPI.new(self)
end
def query
QueryAPI.new(self)
end
class SchemaAPI
def initialize(client)
@client = client
end
def get
response = @client.conn.get("/v1/schema")
response.body
end
def create(schema)
response = @client.conn.post("/v1/schema") do |req|
req.body = schema
end
response.body
end
end
class ObjectsAPI
def initialize(client)
@client = client
end
def create(class_name:, properties:, id: nil)
payload = {
class: class_name,
properties: properties
}
payload[:id] = id if id
response = @client.conn.post("/v1/objects") do |req|
req.body = payload
end
response.body
end
def delete(class_name:, id:)
response = @client.conn.delete("/v1/objects/#{class_name}/#{id}")
response.status == 204
end
end
class QueryAPI
def initialize(client)
@client = client
end
def get(class_name:, fields:, limit: 10, offset: 0, bm25: nil, where: nil)
# Build GraphQL query for Weaviate
query_parts = []
query_parts << "limit: #{limit}"
query_parts << "offset: #{offset}" if offset > 0
if bm25
query_parts << "bm25: { query: \"#{bm25[:query]}\" }"
end
if where
where_clause = build_where_clause(where)
query_parts << "where: #{where_clause}"
end
graphql_query = {
query: "{
Get {
#{class_name}(#{query_parts.join(', ')}) {
#{fields}
}
}
}"
}
response = @client.conn.post("/v1/graphql") do |req|
req.body = graphql_query
end
response.body
end
private
def build_where_clause(where)
operator = where[:operator] || "Equal"
path = where[:path]
value_key = where.keys.find { |k| k.to_s.start_with?("value") }
value = where[value_key]
value_str = value.is_a?(String) ? "\"#{value}\"" : value.to_s
"{
path: [\"#{path.join('", "')}\"],
operator: #{operator},
#{value_key}: #{value_str}
}"
end
end
end
WEAVIATE_CLIENT = WeaviateClient.new(
ENV.fetch("WEAVIATE_URL", "http://localhost:8080")
)
# Schema will be created automatically when needed
# The Document model will handle schema creation