-
Notifications
You must be signed in to change notification settings - Fork 117
/
Requests.hs
1320 lines (1200 loc) · 49 KB
/
Requests.hs
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- |
-- Module : Database.Bloodhound.Common.Requests
-- Copyright : (C) 2014, 2018 Chris Allen
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Chris Allen <[email protected]>
-- Stability : provisional
-- Portability : GHC
--
-- Request to be run against Elasticsearch servers..
module Database.Bloodhound.Common.Requests
( -- * Bloodhound client functions
-- ** Indices
createIndex,
createIndexWith,
flushIndex,
deleteIndex,
updateIndexSettings,
getIndexSettings,
forceMergeIndex,
indexExists,
openIndex,
closeIndex,
listIndices,
catIndices,
waitForYellowIndex,
HealthStatus (..),
-- *** Index Aliases
updateIndexAliases,
getIndexAliases,
deleteIndexAlias,
-- *** Index Templates
putTemplate,
templateExists,
deleteTemplate,
-- ** Mapping
putMapping,
-- ** Documents
indexDocument,
updateDocument,
updateByQuery,
getDocument,
documentExists,
deleteDocument,
deleteByQuery,
IndexedDocument (..),
DeletedDocuments (..),
DeletedDocumentsRetries (..),
-- ** Searching
searchAll,
searchByIndex,
searchByIndices,
searchByIndexTemplate,
searchByIndicesTemplate,
getInitialScroll,
getInitialSortedScroll,
advanceScroll,
refreshIndex,
mkSearch,
mkAggregateSearch,
mkHighlightSearch,
mkSearchTemplate,
bulk,
pageSearch,
mkShardCount,
mkReplicaCount,
getStatus,
dispatchSearch,
-- ** Templates
storeSearchTemplate,
getSearchTemplate,
deleteSearchTemplate,
-- ** Snapshot/Restore
-- *** Snapshot Repos
getSnapshotRepos,
updateSnapshotRepo,
verifySnapshotRepo,
deleteSnapshotRepo,
-- *** Snapshots
createSnapshot,
getSnapshots,
deleteSnapshot,
-- *** Restoring Snapshots
restoreSnapshot,
-- *** Reindex
reindex,
reindexAsync,
-- *** Task
getTask,
-- ** Nodes
getNodesInfo,
getNodesStats,
-- ** Request Utilities
encodeBulkOperations,
encodeBulkOperation,
-- * BHResponse-handling tools
isVersionConflict,
isSuccess,
isCreated,
parseEsResponse,
parseEsResponseWith,
decodeResponse,
eitherDecodeResponse,
-- * Count
countByIndex,
-- * Generic
Acknowledged (..),
Accepted (..),
IgnoredBody (..),
-- * Performing Requests
tryPerformBHRequest,
performBHRequest,
withBHResponse,
withBHResponse_,
withBHResponseParsedEsResponse,
keepBHResponse,
joinBHResponse,
)
where
import Control.Applicative as A
import Control.Monad
import Data.Aeson
import Data.Aeson.Key
import qualified Data.Aeson.KeyMap as X
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Foldable (toList)
import qualified Data.List as LS (foldl')
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe (catMaybes)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock
import qualified Data.Vector as V
import Database.Bloodhound.Client.Cluster
import Database.Bloodhound.Common.Types
import Database.Bloodhound.Internal.Utils.Imports (showText)
import Database.Bloodhound.Internal.Utils.Requests
import Prelude hiding (filter, head)
-- | 'mkShardCount' is a straight-forward smart constructor for 'ShardCount'
-- which rejects 'Int' values below 1 and above 1000.
--
-- >>> mkShardCount 10
-- Just (ShardCount 10)
mkShardCount :: Int -> Maybe ShardCount
mkShardCount n
| n < 1 = Nothing
| n > 1000 = Nothing
| otherwise = Just (ShardCount n)
-- | 'mkReplicaCount' is a straight-forward smart constructor for 'ReplicaCount'
-- which rejects 'Int' values below 0 and above 1000.
--
-- >>> mkReplicaCount 10
-- Just (ReplicaCount 10)
mkReplicaCount :: Int -> Maybe ReplicaCount
mkReplicaCount n
| n < 0 = Nothing
| n > 1000 = Nothing -- ...
| otherwise = Just (ReplicaCount n)
-- | 'getStatus' fetches the 'Status' of a 'Server'
--
-- >>> serverStatus <- runBH' getStatus
-- >>> fmap tagline (serverStatus)
-- Just "You Know, for Search"
getStatus :: BHRequest StatusDependant Status
getStatus = get []
-- | 'getSnapshotRepos' gets the definitions of a subset of the
-- defined snapshot repos.
getSnapshotRepos :: SnapshotRepoSelection -> BHRequest StatusDependant [GenericSnapshotRepo]
getSnapshotRepos sel =
unGSRs <$> get ["_snapshot", selectorSeg]
where
selectorSeg = case sel of
AllSnapshotRepos -> "_all"
SnapshotRepoList (p :| ps) -> T.intercalate "," (renderPat <$> (p : ps))
renderPat (RepoPattern t) = t
renderPat (ExactRepo (SnapshotRepoName t)) = t
-- | Wrapper to extract the list of 'GenericSnapshotRepo' in the
-- format they're returned in
newtype GSRs = GSRs {unGSRs :: [GenericSnapshotRepo]}
instance FromJSON GSRs where
parseJSON = withObject "Collection of GenericSnapshotRepo" parse
where
parse = fmap GSRs . mapM (uncurry go) . X.toList
go rawName = withObject "GenericSnapshotRepo" $ \o ->
GenericSnapshotRepo (SnapshotRepoName $ toText rawName)
<$> o
.: "type"
<*> o
.: "settings"
-- | Create or update a snapshot repo
updateSnapshotRepo ::
(SnapshotRepo repo) =>
-- | Use 'defaultSnapshotRepoUpdateSettings' if unsure
SnapshotRepoUpdateSettings ->
repo ->
BHRequest StatusIndependant Acknowledged
updateSnapshotRepo SnapshotRepoUpdateSettings {..} repo =
put endpoint (encode body)
where
endpoint = ["_snapshot", snapshotRepoName gSnapshotRepoName] `withQueries` params
params
| repoUpdateVerify = []
| otherwise = [("verify", Just "false")]
body =
object
[ "type" .= gSnapshotRepoType,
"settings" .= gSnapshotRepoSettings
]
GenericSnapshotRepo {..} = toGSnapshotRepo repo
-- | Verify if a snapshot repo is working. __NOTE:__ this API did not
-- make it into Elasticsearch until 1.4. If you use an older version,
-- you will get an error here.
verifySnapshotRepo :: SnapshotRepoName -> BHRequest StatusDependant SnapshotVerification
verifySnapshotRepo (SnapshotRepoName n) =
post ["_snapshot", n, "_verify"] emptyBody
deleteSnapshotRepo :: SnapshotRepoName -> BHRequest StatusIndependant Acknowledged
deleteSnapshotRepo (SnapshotRepoName n) =
delete ["_snapshot", n]
-- | Create and start a snapshot
createSnapshot ::
SnapshotRepoName ->
SnapshotName ->
SnapshotCreateSettings ->
BHRequest StatusIndependant Acknowledged
createSnapshot (SnapshotRepoName repoName) (SnapshotName snapName) SnapshotCreateSettings {..} =
put endpoint body
where
endpoint = ["_snapshot", repoName, snapName] `withQueries` params
params = [("wait_for_completion", Just (boolQP snapWaitForCompletion))]
body = encode $ object prs
prs =
catMaybes
[ ("indices" .=) . indexSelectionName <$> snapIndices,
Just ("ignore_unavailable" .= snapIgnoreUnavailable),
Just ("ignore_global_state" .= snapIncludeGlobalState),
Just ("partial" .= snapPartial)
]
indexSelectionName :: IndexSelection -> Text
indexSelectionName AllIndexes = "_all"
indexSelectionName (IndexList (i :| is)) = T.intercalate "," (unIndexName <$> (i : is))
-- | Get info about known snapshots given a pattern and repo name.
getSnapshots :: SnapshotRepoName -> SnapshotSelection -> BHRequest StatusDependant [SnapshotInfo]
getSnapshots (SnapshotRepoName repoName) sel =
unSIs <$> get ["_snapshot", repoName, snapPath]
where
snapPath = case sel of
AllSnapshots -> "_all"
SnapshotList (s :| ss) -> T.intercalate "," (renderPath <$> (s : ss))
renderPath (SnapPattern t) = t
renderPath (ExactSnap (SnapshotName t)) = t
newtype SIs = SIs {unSIs :: [SnapshotInfo]}
instance FromJSON SIs where
parseJSON = withObject "Collection of SnapshotInfo" parse
where
parse o = SIs <$> o .: "snapshots"
-- | Delete a snapshot. Cancels if it is running.
deleteSnapshot :: SnapshotRepoName -> SnapshotName -> BHRequest StatusIndependant Acknowledged
deleteSnapshot (SnapshotRepoName repoName) (SnapshotName snapName) =
delete ["_snapshot", repoName, snapName]
-- | Restore a snapshot to the cluster See
-- <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/modules-snapshots.html#_restore>
-- for more details.
restoreSnapshot ::
SnapshotRepoName ->
SnapshotName ->
-- | Start with 'defaultSnapshotRestoreSettings' and customize
-- from there for reasonable defaults.
SnapshotRestoreSettings ->
BHRequest StatusIndependant Accepted
restoreSnapshot (SnapshotRepoName repoName) (SnapshotName snapName) SnapshotRestoreSettings {..} =
post endpoint (encode body)
where
endpoint = ["_snapshot", repoName, snapName, "_restore"] `withQueries` params
params = [("wait_for_completion", Just (boolQP snapRestoreWaitForCompletion))]
body =
object $
catMaybes
[ ("indices" .=) . indexSelectionName <$> snapRestoreIndices,
Just ("ignore_unavailable" .= snapRestoreIgnoreUnavailable),
Just ("include_global_state" .= snapRestoreIncludeGlobalState),
("rename_pattern" .=) <$> snapRestoreRenamePattern,
("rename_replacement" .=) . renderTokens <$> snapRestoreRenameReplacement,
Just ("include_aliases" .= snapRestoreIncludeAliases),
("index_settings" .=) <$> snapRestoreIndexSettingsOverrides,
("ignore_index_settings" .=) <$> snapRestoreIgnoreIndexSettings
]
renderTokens (t :| ts) = mconcat (renderToken <$> (t : ts))
renderToken (RRTLit t) = t
renderToken RRSubWholeMatch = "$0"
renderToken (RRSubGroup g) = T.pack (show (rrGroupRefNum g))
getNodesInfo :: NodeSelection -> BHRequest StatusDependant NodesInfo
getNodesInfo sel =
get ["_nodes", selectionSeg]
where
selectionSeg = case sel of
LocalNode -> "_local"
NodeList (l :| ls) -> T.intercalate "," (selToSeg <$> (l : ls))
AllNodes -> "_all"
selToSeg (NodeByName (NodeName n)) = n
selToSeg (NodeByFullNodeId (FullNodeId i)) = i
selToSeg (NodeByHost (Server s)) = s
selToSeg (NodeByAttribute (NodeAttrName a) v) = a <> ":" <> v
getNodesStats :: NodeSelection -> BHRequest StatusDependant NodesStats
getNodesStats sel =
get ["_nodes", selectionSeg, "stats"]
where
selectionSeg = case sel of
LocalNode -> "_local"
NodeList (l :| ls) -> T.intercalate "," (selToSeg <$> (l : ls))
AllNodes -> "_all"
selToSeg (NodeByName (NodeName n)) = n
selToSeg (NodeByFullNodeId (FullNodeId i)) = i
selToSeg (NodeByHost (Server s)) = s
selToSeg (NodeByAttribute (NodeAttrName a) v) = a <> ":" <> v
-- | 'createIndex' will create an index given a 'Server', 'IndexSettings', and an 'IndexName'.
--
-- >>> response <- runBH' $ createIndex defaultIndexSettings (IndexName "didimakeanindex")
-- >>> isSuccess response
-- True
-- >>> runBH' $ indexExists (IndexName "didimakeanindex")
-- True
createIndex :: IndexSettings -> IndexName -> BHRequest StatusDependant Acknowledged
createIndex indexSettings indexName =
put [unIndexName indexName] $ encode indexSettings
-- | Create an index, providing it with any number of settings. This
-- is more expressive than 'createIndex' but makes is more verbose
-- for the common case of configuring only the shard count and
-- replica count.
createIndexWith ::
[UpdatableIndexSetting] ->
-- | shard count
Int ->
IndexName ->
BHRequest StatusIndependant Acknowledged
createIndexWith updates shards indexName =
put [unIndexName indexName] body
where
body =
encode $
object
[ "settings"
.= deepMerge
( X.singleton "index.number_of_shards" (toJSON shards)
: [u | Object u <- toJSON <$> updates]
)
]
-- | 'flushIndex' will flush an index given a 'Server' and an 'IndexName'.
flushIndex :: IndexName -> BHRequest StatusDependant ShardResult
flushIndex indexName =
post [unIndexName indexName, "_flush"] emptyBody
-- | 'deleteIndex' will delete an index given a 'Server' and an 'IndexName'.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings (IndexName "didimakeanindex")
-- >>> response <- runBH' $ deleteIndex (IndexName "didimakeanindex")
-- >>> isSuccess response
-- True
-- >>> runBH' $ indexExists (IndexName "didimakeanindex")
-- False
deleteIndex :: IndexName -> BHRequest StatusDependant Acknowledged
deleteIndex indexName =
delete [unIndexName indexName]
-- | 'updateIndexSettings' will apply a non-empty list of setting updates to an index
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings (IndexName "unconfiguredindex")
-- >>> response <- runBH' $ updateIndexSettings (BlocksWrite False :| []) (IndexName "unconfiguredindex")
-- >>> isSuccess response
-- True
updateIndexSettings ::
NonEmpty UpdatableIndexSetting ->
IndexName ->
BHRequest StatusIndependant Acknowledged
updateIndexSettings updates indexName =
put [unIndexName indexName, "_settings"] (encode body)
where
body = Object (deepMerge [u | Object u <- toJSON <$> toList updates])
getIndexSettings :: IndexName -> BHRequest StatusDependant IndexSettingsSummary
getIndexSettings indexName =
get [unIndexName indexName, "_settings"]
-- | 'forceMergeIndex'
--
-- The force merge API allows to force merging of one or more indices through
-- an API. The merge relates to the number of segments a Lucene index holds
-- within each shard. The force merge operation allows to reduce the number of
-- segments by merging them.
--
-- This call will block until the merge is complete. If the http connection is
-- lost, the request will continue in the background, and any new requests will
-- block until the previous force merge is complete.
-- For more information see
-- <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html#indices-forcemerge>.
-- Nothing
-- worthwhile comes back in the response body, so matching on the status
-- should suffice.
--
-- 'forceMergeIndex' with a maxNumSegments of 1 and onlyExpungeDeletes
-- to True is the main way to release disk space back to the OS being
-- held by deleted documents.
--
-- >>> let ixn = IndexName "unoptimizedindex"
-- >>> _ <- runBH' $ deleteIndex ixn >> createIndex defaultIndexSettings ixn
-- >>> response <- runBH' $ forceMergeIndex (IndexList (ixn :| [])) (defaultIndexOptimizationSettings { maxNumSegments = Just 1, onlyExpungeDeletes = True })
-- >>> isSuccess response
-- True
forceMergeIndex :: IndexSelection -> ForceMergeIndexSettings -> BHRequest StatusDependant ShardsResult
forceMergeIndex ixs ForceMergeIndexSettings {..} =
post endpoint emptyBody
where
endpoint = [indexName, "_forcemerge"] `withQueries` params
params =
catMaybes
[ ("max_num_segments",) . Just . showText <$> maxNumSegments,
Just ("only_expunge_deletes", Just (boolQP onlyExpungeDeletes)),
Just ("flush", Just (boolQP flushAfterOptimize))
]
indexName = indexSelectionName ixs
deepMerge :: [Object] -> Object
deepMerge = LS.foldl' (X.unionWith merge) mempty
where
merge (Object a) (Object b) = Object (deepMerge [a, b])
merge _ b = b
doesExist :: Endpoint -> BHRequest StatusDependant Bool
doesExist =
withBHResponse_ isSuccess . head' @StatusDependant @IgnoredBody
-- | 'indexExists' enables you to check if an index exists. Returns 'Bool'
-- in IO
--
-- >>> exists <- runBH' $ indexExists testIndex
indexExists :: IndexName -> BHRequest StatusDependant Bool
indexExists indexName =
doesExist [unIndexName indexName]
-- | 'refreshIndex' will force a refresh on an index. You must
-- do this if you want to read what you wrote.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
-- >>> _ <- runBH' $ refreshIndex testIndex
refreshIndex :: IndexName -> BHRequest StatusDependant ShardResult
refreshIndex indexName =
post [unIndexName indexName, "_refresh"] emptyBody
-- | Block until the index becomes available for indexing
-- documents. This is useful for integration tests in which
-- indices are rapidly created and deleted.
waitForYellowIndex :: IndexName -> BHRequest StatusIndependant HealthStatus
waitForYellowIndex indexName =
get endpoint
where
endpoint = ["_cluster", "health", unIndexName indexName] `withQueries` params
params = [("wait_for_status", Just "yellow"), ("timeout", Just "10s")]
data HealthStatus = HealthStatus
{ healthStatusClusterName :: Text,
healthStatusStatus :: Text,
healthStatusTimedOut :: Bool,
healthStatusNumberOfNodes :: Int,
healthStatusNumberOfDataNodes :: Int,
healthStatusActivePrimaryShards :: Int,
healthStatusActiveShards :: Int,
healthStatusRelocatingShards :: Int,
healthStatusInitializingShards :: Int,
healthStatusUnassignedShards :: Int,
healthStatusDelayedUnassignedShards :: Int,
healthStatusNumberOfPendingTasks :: Int,
healthStatusNumberOfInFlightFetch :: Int,
healthStatusTaskMaxWaitingInQueueMillis :: Int,
healthStatusActiveShardsPercentAsNumber :: Float
}
deriving stock (Eq, Show)
instance FromJSON HealthStatus where
parseJSON =
withObject "HealthStatus" $ \v ->
HealthStatus
<$> v
.: "cluster_name"
<*> v
.: "status"
<*> v
.: "timed_out"
<*> v
.: "number_of_nodes"
<*> v
.: "number_of_data_nodes"
<*> v
.: "active_primary_shards"
<*> v
.: "active_shards"
<*> v
.: "relocating_shards"
<*> v
.: "initializing_shards"
<*> v
.: "unassigned_shards"
<*> v
.: "delayed_unassigned_shards"
<*> v
.: "number_of_pending_tasks"
<*> v
.: "number_of_in_flight_fetch"
<*> v
.: "task_max_waiting_in_queue_millis"
<*> v
.: "active_shards_percent_as_number"
openOrCloseIndexes :: OpenCloseIndex -> IndexName -> BHRequest StatusIndependant Acknowledged
openOrCloseIndexes oci indexName =
post [unIndexName indexName, stringifyOCIndex] emptyBody
where
stringifyOCIndex = case oci of
OpenIndex -> "_open"
CloseIndex -> "_close"
-- | 'openIndex' opens an index given a 'Server' and an 'IndexName'. Explained in further detail at
-- <http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html>
--
-- >>> response <- runBH' $ openIndex testIndex
openIndex :: IndexName -> BHRequest StatusIndependant Acknowledged
openIndex = openOrCloseIndexes OpenIndex
-- | 'closeIndex' closes an index given a 'Server' and an 'IndexName'. Explained in further detail at
-- <http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html>
--
-- >>> response <- runBH' $ closeIndex testIndex
closeIndex :: IndexName -> BHRequest StatusIndependant Acknowledged
closeIndex = openOrCloseIndexes CloseIndex
-- | 'listIndices' returns a list of all index names on a given 'Server'
listIndices :: BHRequest StatusDependant [IndexName]
listIndices =
map unListedIndexName <$> get ["_cat/indices?format=json"]
newtype ListedIndexName = ListedIndexName {unListedIndexName :: IndexName}
deriving stock (Eq, Show)
instance FromJSON ListedIndexName where
parseJSON =
withObject "ListedIndexName" $ \o ->
ListedIndexName <$> o .: "index"
-- | 'catIndices' returns a list of all index names on a given 'Server' as well as their doc counts
catIndices :: BHRequest StatusDependant [(IndexName, Int)]
catIndices =
map unListedIndexNameWithCount <$> get ["_cat/indices?format=json"]
newtype ListedIndexNameWithCount = ListedIndexNameWithCount {unListedIndexNameWithCount :: (IndexName, Int)}
deriving stock (Eq, Show)
instance FromJSON ListedIndexNameWithCount where
parseJSON =
withObject "ListedIndexNameWithCount" $ \o -> do
xs <- (,) <$> o .: "index" <*> o .: "docs.count"
return $ ListedIndexNameWithCount xs
-- | 'updateIndexAliases' updates the server's index alias
-- table. Operations are atomic. Explained in further detail at
-- <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>
--
-- >>> let src = IndexName "a-real-index"
-- >>> let aliasName = IndexName "an-alias"
-- >>> let iAlias = IndexAlias src (IndexAliasName aliasName)
-- >>> let aliasCreate = IndexAliasCreate Nothing Nothing
-- >>> _ <- runBH' $ deleteIndex src
-- >>> isSuccess <$> runBH' (createIndex defaultIndexSettings src)
-- True
-- >>> runBH' $ indexExists src
-- True
-- >>> isSuccess <$> runBH' (updateIndexAliases (AddAlias iAlias aliasCreate :| []))
-- True
-- >>> runBH' $ indexExists aliasName
-- True
updateIndexAliases :: NonEmpty IndexAliasAction -> BHRequest StatusIndependant Acknowledged
updateIndexAliases actions =
post ["_aliases"] (encode body)
where
body = object ["actions" .= toList actions]
-- | Get all aliases configured on the server.
getIndexAliases :: BHRequest StatusDependant IndexAliasesSummary
getIndexAliases =
get ["_aliases"]
-- | Delete a single alias, removing it from all indices it
-- is currently associated with.
deleteIndexAlias :: IndexAliasName -> BHRequest StatusIndependant Acknowledged
deleteIndexAlias (IndexAliasName name) =
delete ["_all", "_alias", unIndexName name]
-- | 'putTemplate' creates a template given an 'IndexTemplate' and a 'TemplateName'.
-- Explained in further detail at
-- <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html>
--
-- >>> let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
-- >>> resp <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")
putTemplate :: IndexTemplate -> TemplateName -> BHRequest StatusIndependant Acknowledged
putTemplate indexTemplate (TemplateName templateName) =
put ["_template", templateName] (encode indexTemplate)
-- | 'templateExists' checks to see if a template exists.
--
-- >>> exists <- runBH' $ templateExists (TemplateName "tweet-tpl")
templateExists :: TemplateName -> BHRequest StatusDependant Bool
templateExists (TemplateName templateName) =
doesExist ["_template", templateName]
-- | 'deleteTemplate' is an HTTP DELETE and deletes a template.
--
-- >>> let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
-- >>> _ <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")
-- >>> resp <- runBH' $ deleteTemplate (TemplateName "tweet-tpl")
deleteTemplate :: TemplateName -> BHRequest StatusIndependant Acknowledged
deleteTemplate (TemplateName templateName) =
delete ["_template", templateName]
-- | 'putMapping' is an HTTP PUT and has upsert semantics. Mappings are schemas
-- for documents in indexes.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
-- >>> resp <- runBH' $ putMapping testIndex TweetMapping
-- >>> print resp
-- Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("content-type","application/json; charset=UTF-8"),("content-encoding","gzip"),("transfer-encoding","chunked")], responseBody = "{\"acknowledged\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}
putMapping :: (FromJSON r, ToJSON a) => IndexName -> a -> BHRequest StatusDependant r
putMapping indexName mapping =
-- "_mapping" above is originally transposed
-- erroneously. The correct API call is: "/INDEX/_mapping"
put [unIndexName indexName, "_mapping"] (encode mapping)
{-# DEPRECATED putMapping "See <https://www.elastic.co/guide/en/elasticsearch/reference/7.17/removal-of-types.html>" #-}
versionCtlParams :: IndexDocumentSettings -> [(Text, Maybe Text)]
versionCtlParams cfg =
case idsVersionControl cfg of
NoVersionControl -> []
InternalVersion v -> versionParams v "internal"
ExternalGT (ExternalDocVersion v) -> versionParams v "external_gt"
ExternalGTE (ExternalDocVersion v) -> versionParams v "external_gte"
ForceVersion (ExternalDocVersion v) -> versionParams v "force"
where
vt = showText . docVersionNumber
versionParams :: DocVersion -> Text -> [(Text, Maybe Text)]
versionParams v t =
[ ("version", Just $ vt v),
("version_type", Just t)
]
-- | 'indexDocument' is the primary way to save a single document in
-- Elasticsearch. The document itself is simply something we can
-- convert into a JSON 'Value'. The 'DocId' will function as the
-- primary key for the document. You are encouraged to generate
-- your own id's and not rely on Elasticsearch's automatic id
-- generation. Read more about it here:
-- https://github.com/bitemyapp/bloodhound/issues/107
--
-- >>> resp <- runBH' $ indexDocument testIndex defaultIndexDocumentSettings exampleTweet (DocId "1")
-- >>> print resp
-- Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("content-type","application/json; charset=UTF-8"),("content-encoding","gzip"),("content-length","152")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"_doc\",\"_id\":\"1\",\"_version\":2,\"result\":\"updated\",\"_shards\":{\"total\":1,\"successful\":1,\"failed\":0},\"_seq_no\":1,\"_primary_term\":1}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}
indexDocument ::
(ToJSON doc) =>
IndexName ->
IndexDocumentSettings ->
doc ->
DocId ->
BHRequest StatusDependant IndexedDocument
indexDocument indexName cfg document (DocId docId) =
put endpoint (encode body)
where
endpoint = [unIndexName indexName, "_doc", docId] `withQueries` indexQueryString cfg (DocId docId)
body = encodeDocument cfg document
data IndexedDocument = IndexedDocument
{ idxDocIndex :: Text,
idxDocType :: Maybe Text,
idxDocId :: Text,
idxDocVersion :: Int,
idxDocResult :: Text,
idxDocShards :: ShardResult,
idxDocSeqNo :: Int,
idxDocPrimaryTerm :: Int
}
deriving stock (Eq, Show)
{-# DEPRECATED idxDocType "deprecated since ElasticSearch 6.0" #-}
instance FromJSON IndexedDocument where
parseJSON =
withObject "IndexedDocument" $ \v ->
IndexedDocument
<$> v
.: "_index"
<*> v
.:? "_type"
<*> v
.: "_id"
<*> v
.: "_version"
<*> v
.: "result"
<*> v
.: "_shards"
<*> v
.: "_seq_no"
<*> v
.: "_primary_term"
-- | 'updateDocument' provides a way to perform an partial update of a
-- an already indexed document.
updateDocument ::
(ToJSON patch) =>
IndexName ->
IndexDocumentSettings ->
patch ->
DocId ->
BHRequest StatusDependant IndexedDocument
updateDocument indexName cfg patch (DocId docId) =
post endpoint (encode body)
where
endpoint = [unIndexName indexName, "_update", docId] `withQueries` indexQueryString cfg (DocId docId)
body = object ["doc" .= encodeDocument cfg patch]
updateByQuery ::
(FromJSON a) =>
IndexName ->
Query ->
Maybe Script ->
BHRequest StatusDependant a
updateByQuery indexName q mScript =
post endpoint (encode body)
where
endpoint = [unIndexName indexName, "_update_by_query"]
body = Object $ ("query" .= q) <> scriptObject
scriptObject :: X.KeyMap Value
scriptObject = case toJSON mScript of
Null -> mempty
Object o -> o
x -> "script" .= x
{- From ES docs:
Parent and child documents must be indexed on the same shard.
This means that the same routing value needs to be provided when getting, deleting, or updating a child document.
Parent/Child support in Bloodhound requires MUCH more love.
To work it around for now (and to support the existing unit test) we route "parent" documents to their "_id"
(which is the default strategy for the ES), and route all child documents to their parens' "_id"
However, it may not be flexible enough for some corner cases.
Buld operations are completely unaware of "routing" and are probably broken in that matter.
Or perhaps they always were, because the old "_parent" would also have this requirement.
-}
indexQueryString :: IndexDocumentSettings -> DocId -> [(Text, Maybe Text)]
indexQueryString cfg (DocId docId) =
versionCtlParams cfg <> routeParams
where
routeParams = case idsJoinRelation cfg of
Nothing -> []
Just (ParentDocument _ _) -> [("routing", Just docId)]
Just (ChildDocument _ _ (DocId pid)) -> [("routing", Just pid)]
encodeDocument :: (ToJSON doc) => IndexDocumentSettings -> doc -> Value
encodeDocument cfg document =
case idsJoinRelation cfg of
Nothing -> toJSON document
Just (ParentDocument (FieldName field) name) ->
mergeObjects (toJSON document) (object [fromText field .= name])
Just (ChildDocument (FieldName field) name parent) ->
mergeObjects (toJSON document) (object [fromText field .= object ["name" .= name, "parent" .= parent]])
where
mergeObjects (Object a) (Object b) = Object (a <> b)
mergeObjects _ _ = error "Impossible happened: both document body and join parameters must be objects"
-- | 'deleteDocument' is the primary way to delete a single document.
--
-- >>> _ <- runBH' $ deleteDocument testIndex (DocId "1")
deleteDocument :: IndexName -> DocId -> BHRequest StatusDependant IndexedDocument
deleteDocument indexName (DocId docId) =
delete [unIndexName indexName, "_doc", docId]
-- | 'deleteByQuery' performs a deletion on every document that matches a query.
--
-- >>> let query = TermQuery (Term "user" "bitemyapp") Nothing
-- >>> _ <- runBH' $ deleteDocument testIndex query
deleteByQuery :: IndexName -> Query -> BHRequest StatusDependant DeletedDocuments
deleteByQuery indexName query =
post [unIndexName indexName, "_delete_by_query"] (encode body)
where
body = object ["query" .= query]
data DeletedDocuments = DeletedDocuments
{ delDocsTook :: Int,
delDocsTimedOut :: Bool,
delDocsTotal :: Int,
delDocsDeleted :: Int,
delDocsBatches :: Int,
delDocsVersionConflicts :: Int,
delDocsNoops :: Int,
delDocsRetries :: DeletedDocumentsRetries,
delDocsThrottledMillis :: Int,
delDocsRequestsPerSecond :: Float,
delDocsThrottledUntilMillis :: Int,
delDocsFailures :: [Value] -- TODO find examples
}
deriving stock (Eq, Show)
instance FromJSON DeletedDocuments where
parseJSON =
withObject "DeletedDocuments" $ \v ->
DeletedDocuments
<$> v
.: "took"
<*> v
.: "timed_out"
<*> v
.: "total"
<*> v
.: "deleted"
<*> v
.: "batches"
<*> v
.: "version_conflicts"
<*> v
.: "noops"
<*> v
.: "retries"
<*> v
.: "throttled_millis"
<*> v
.: "requests_per_second"
<*> v
.: "throttled_until_millis"
<*> v
.: "failures"
data DeletedDocumentsRetries = DeletedDocumentsRetries
{ delDocsRetriesBulk :: Int,
delDocsRetriesSearch :: Int
}
deriving stock (Eq, Show)
instance FromJSON DeletedDocumentsRetries where
parseJSON =
withObject "DeletedDocumentsRetries" $ \v ->
DeletedDocumentsRetries
<$> v
.: "bulk"
<*> v
.: "search"
-- | 'bulk' uses
-- <http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html Elasticsearch's bulk API>
-- to perform bulk operations. The 'BulkOperation' data type encodes the
-- index\/update\/delete\/create operations. You pass a 'V.Vector' of 'BulkOperation's
-- and a 'Server' to 'bulk' in order to send those operations up to your Elasticsearch
-- server to be performed. I changed from [BulkOperation] to a Vector due to memory overhead.
--
-- >>> let stream = V.fromList [BulkIndex testIndex (DocId "2") (toJSON (BulkTest "blah"))]
-- >>> _ <- runBH' $ bulk stream
-- >>> _ <- runBH' $ refreshIndex testIndex
bulk ::
(ParseBHResponse contextualized) =>
V.Vector BulkOperation ->
BHRequest contextualized BulkResponse
bulk =
post ["_bulk"] . encodeBulkOperations
-- | 'encodeBulkOperations' is a convenience function for dumping a vector of 'BulkOperation'
-- into an 'L.ByteString'
--
-- >>> let bulkOps = V.fromList [BulkIndex testIndex (DocId "2") (toJSON (BulkTest "blah"))]
-- >>> encodeBulkOperations bulkOps
-- "\n{\"index\":{\"_id\":\"2\",\"_index\":\"twitter\"}}\n{\"name\":\"blah\"}\n"
encodeBulkOperations :: V.Vector BulkOperation -> L.ByteString
encodeBulkOperations stream = collapsed
where
blobs =
fmap encodeBulkOperation stream
mashedTaters =
mash (mempty :: Builder) blobs
collapsed =
toLazyByteString $ mappend mashedTaters (byteString "\n")
mash :: Builder -> V.Vector L.ByteString -> Builder
mash = V.foldl' (\b x -> b <> byteString "\n" <> lazyByteString x)
mkBulkStreamValue :: Text -> IndexName -> Text -> Value
mkBulkStreamValue operation indexName docId =
object
[ fromText operation
.= object
[ "_index" .= indexName,
"_id" .= docId
]
]
mkBulkStreamValueAuto :: Text -> IndexName -> Value
mkBulkStreamValueAuto operation indexName =
object
[ fromText operation
.= object ["_index" .= indexName]
]
mkBulkStreamValueWithMeta :: [UpsertActionMetadata] -> Text -> IndexName -> Text -> Value
mkBulkStreamValueWithMeta meta operation indexName docId =
object
[ fromText operation
.= object
( [ "_index" .= indexName,
"_id" .= docId
]
<> (buildUpsertActionMetadata <$> meta)
)
]
-- | 'encodeBulkOperation' is a convenience function for dumping a single 'BulkOperation'
-- into an 'L.ByteString'
--
-- >>> let bulkOp = BulkIndex testIndex (DocId "2") (toJSON (BulkTest "blah"))
-- >>> encodeBulkOperation bulkOp
-- "{\"index\":{\"_id\":\"2\",\"_index\":\"twitter\"}}\n{\"name\":\"blah\"}"
encodeBulkOperation :: BulkOperation -> L.ByteString
encodeBulkOperation (BulkIndex indexName (DocId docId) value) = blob
where
metadata = mkBulkStreamValue "index" indexName docId
blob = encode metadata `mappend` "\n" `mappend` encode value
encodeBulkOperation (BulkIndexAuto indexName value) = blob
where
metadata = mkBulkStreamValueAuto "index" indexName
blob = encode metadata `mappend` "\n" `mappend` encode value
encodeBulkOperation (BulkIndexEncodingAuto indexName encoding) = toLazyByteString blob
where
metadata = toEncoding (mkBulkStreamValueAuto "index" indexName)
blob = fromEncoding metadata <> "\n" <> fromEncoding encoding
encodeBulkOperation (BulkCreate indexName (DocId docId) value) = blob
where
metadata = mkBulkStreamValue "create" indexName docId
blob = encode metadata `mappend` "\n" `mappend` encode value
encodeBulkOperation (BulkDelete indexName (DocId docId)) = blob
where
metadata = mkBulkStreamValue "delete" indexName docId
blob = encode metadata
encodeBulkOperation (BulkUpdate indexName (DocId docId) value) = blob
where
metadata = mkBulkStreamValue "update" indexName docId
doc = object ["doc" .= value]
blob = encode metadata `mappend` "\n" `mappend` encode doc
encodeBulkOperation
( BulkUpsert