forked from typesense/typesense-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocuments.rb
More file actions
94 lines (77 loc) · 2.77 KB
/
documents.rb
File metadata and controls
94 lines (77 loc) · 2.77 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
# frozen_string_literal: true
require 'json'
module Typesense
class Documents
RESOURCE_PATH = '/documents'
def initialize(collection_name, api_call)
@collection_name = collection_name
@api_call = api_call
@documents = {}
end
def create(document, options = {})
@api_call.post(endpoint_path, document, options)
end
def upsert(document, options = {})
@api_call.post(endpoint_path, document, options.merge(action: :upsert))
end
def update(document, options = {})
if options['filter_by'] || options[:filter_by]
@api_call.patch(endpoint_path, document, options)
else
@api_call.post(endpoint_path, document, options.merge(action: :update))
end
end
def create_many(documents, options = {})
@api_call.logger.warn('#create_many is deprecated and will be removed in a future version. Use #import instead, which now takes both an array of documents or a JSONL string of documents')
import(documents, options)
end
# @param [Array,String] documents An array of document hashes or a JSONL string of documents.
def import(documents, options = {})
documents_in_jsonl_format = if documents.is_a?(Array)
documents.map { |document| JSON.dump(document) }.join("\n")
else
documents
end
results_in_jsonl_format = @api_call.perform_request(
'post',
endpoint_path('import'),
query_parameters: options,
body_parameters: documents_in_jsonl_format,
additional_headers: { 'Content-Type' => 'text/plain' }
)
if documents.is_a?(Array)
results_in_jsonl_format.split("\n").map do |r|
JSON.parse(r)
rescue JSON::ParserError => e
{
'success' => false,
'exception' => e.class.name,
'error' => e.message,
'json' => r
}
end
else
results_in_jsonl_format
end
end
def export(options = {})
@api_call.get(endpoint_path('export'), options)
end
def search(search_parameters)
@api_call.get(endpoint_path('search'), search_parameters)
end
def [](document_id)
@documents[document_id] ||= Document.new(@collection_name, document_id, @api_call)
end
def delete(query_parameters = {})
@api_call.delete(endpoint_path, query_parameters)
end
def truncate
@api_call.delete(endpoint_path, { truncate: true })
end
private
def endpoint_path(operation = nil)
"#{Collections::RESOURCE_PATH}/#{URI.encode_www_form_component(@collection_name)}#{Documents::RESOURCE_PATH}#{"/#{operation}" unless operation.nil?}"
end
end
end