2 Module : Gargantext.API.Ngrams
3 Description : Server API
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
13 get ngrams filtered by NgramsType
18 {-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
20 {-# LANGUAGE ConstraintKinds #-}
21 {-# LANGUAGE ScopedTypeVariables #-}
22 {-# LANGUAGE TypeOperators #-}
23 {-# LANGUAGE TypeFamilies #-}
25 module Gargantext.API.Ngrams
32 --, rmListNgrams TODO fix before exporting
33 , apiNgramsTableCorpus
56 , NgramsRepoElement(..)
77 , VersionedWithCount(..)
79 , listNgramsChangedSince
83 import Control.Concurrent
84 import Control.Lens ((.~), view, (^.), (^..), (+~), (%~), (.~), sumOf, at, _Just, Each(..), (%%~), mapped, ifolded, withIndex)
85 import Control.Monad.Reader
86 import Data.Aeson hiding ((.=))
87 import Data.Either (Either(..))
89 import Data.Map.Strict (Map)
90 import Data.Maybe (fromMaybe)
92 import Data.Ord (Down(..))
93 import Data.Patch.Class (Action(act), Transformable(..), ours)
94 import Data.Swagger hiding (version, patch)
95 import Data.Text (Text, isInfixOf, unpack)
96 import Data.Text.Lazy.IO as DTL
97 import Formatting (hprint, int, (%))
98 import GHC.Generics (Generic)
99 import Gargantext.API.Admin.Orchestrator.Types (JobLog(..), AsyncJobs)
100 import Gargantext.API.Admin.Types (HasSettings)
101 import Gargantext.API.Job
102 import Gargantext.API.Ngrams.Types
103 import Gargantext.API.Prelude
104 import Gargantext.Core.NodeStory
105 import Gargantext.Core.Types (ListType(..), NodeId, ListId, DocId, Limit, Offset, TODO, assertValid, HasInvalidError)
106 import Gargantext.API.Ngrams.Tools
107 import Gargantext.Database.Action.Flow.Types
108 import Gargantext.Database.Action.Metrics.NgramsByNode (getOccByNgramsOnlyFast')
109 import Gargantext.Database.Admin.Config (userMaster)
110 import Gargantext.Database.Admin.Types.Node (NodeType(..))
111 import Gargantext.Database.Prelude (HasConnectionPool, HasConfig)
112 import Gargantext.Database.Query.Table.Ngrams hiding (NgramsType(..), ngramsType, ngrams_terms)
113 import Gargantext.Database.Query.Table.Node (getNode)
114 import Gargantext.Database.Query.Table.Node.Error (HasNodeError)
115 import Gargantext.Database.Query.Table.Node.Select
116 import Gargantext.Database.Schema.Node (node_id, node_parent_id, node_user_id)
117 import Gargantext.Prelude hiding (log)
118 import Gargantext.Prelude.Clock (hasTime, getTime)
119 import Prelude (error)
120 import Servant hiding (Patch)
121 import Servant.Job.Async (JobFunction(..), serveJobsAPI)
122 import System.IO (stderr)
123 import Test.QuickCheck (elements)
124 import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
125 import qualified Data.Aeson.Text as DAT
126 import qualified Data.List as List
127 import qualified Data.Map.Strict as Map
128 import qualified Data.Map.Strict.Patch as PM
129 import qualified Data.Set as S
130 import qualified Data.Set as Set
131 import qualified Gargantext.API.Metrics as Metrics
132 import qualified Gargantext.Database.Query.Table.Ngrams as TableNgrams
135 -- TODO sequences of modifications (Patchs)
136 type NgramsIdPatch = Patch NgramsId NgramsPatch
138 ngramsPatch :: Int -> NgramsPatch
139 ngramsPatch n = NgramsPatch (DM.fromList [(1, StopTerm)]) (Set.fromList [n]) Set.empty
141 toEdit :: NgramsId -> NgramsPatch -> Edit NgramsId NgramsPatch
142 toEdit n p = Edit n p
143 ngramsIdPatch :: Patch NgramsId NgramsPatch
144 ngramsIdPatch = fromList $ catMaybes $ reverse [ replace (1::NgramsId) (Just $ ngramsPatch 1) Nothing
145 , replace (1::NgramsId) Nothing (Just $ ngramsPatch 2)
146 , replace (2::NgramsId) Nothing (Just $ ngramsPatch 2)
149 -- applyPatchBack :: Patch -> IO Patch
150 -- isEmptyPatch = Map.all (\x -> Set.isEmpty (add_children x) && Set.isEmpty ... )
152 ------------------------------------------------------------------------
153 ------------------------------------------------------------------------
154 ------------------------------------------------------------------------
157 -- TODO: Replace.old is ignored which means that if the current list
158 -- `MapTerm` and that the patch is `Replace CandidateTerm StopTerm` then
159 -- the list is going to be `StopTerm` while it should keep `MapTerm`.
160 -- However this should not happen in non conflicting situations.
161 mkListsUpdate :: NgramsType -> NgramsTablePatch -> [(NgramsTypeId, NgramsTerm, ListTypeId)]
162 mkListsUpdate nt patches =
163 [ (ngramsTypeId nt, ng, listTypeId lt)
164 | (ng, patch) <- patches ^.. ntp_ngrams_patches . ifolded . withIndex
165 , lt <- patch ^.. patch_list . new
168 mkChildrenGroups :: (PatchSet NgramsTerm -> Set NgramsTerm)
171 -> [(NgramsTypeId, NgramsParent, NgramsChild)]
172 mkChildrenGroups addOrRem nt patches =
173 [ (ngramsTypeId nt, parent, child)
174 | (parent, patch) <- patches ^.. ntp_ngrams_patches . ifolded . withIndex
175 , child <- patch ^.. patch_children . to addOrRem . folded
179 ------------------------------------------------------------------------
181 saveNodeStory :: ( MonadReader env m, MonadBase IO m, HasNodeStorySaver env )
183 saveNodeStory = liftBase =<< view hasNodeStorySaver
186 listTypeConflictResolution :: ListType -> ListType -> ListType
187 listTypeConflictResolution _ _ = undefined -- TODO Use Map User ListType
190 ngramsStatePatchConflictResolution
191 :: TableNgrams.NgramsType
193 -> ConflictResolutionNgramsPatch
194 ngramsStatePatchConflictResolution _ngramsType _ngramsTerm
195 = (ours, (const ours, ours), (False, False))
196 -- (False, False) mean here that Mod has always priority.
197 -- (True, False) <- would mean priority to the left (same as ours).
198 -- undefined {- TODO think this through -}, listTypeConflictResolution)
204 -- Insertions are not considered as patches,
205 -- they do not extend history,
206 -- they do not bump version.
207 insertNewOnly :: a -> Maybe b -> a
208 insertNewOnly m = maybe m (const $ error "insertNewOnly: impossible")
209 -- TODO error handling
212 -- TODO refactor with putListNgrams
213 copyListNgrams :: RepoCmdM env err m
214 => NodeId -> NodeId -> NgramsType
216 copyListNgrams srcListId dstListId ngramsType = do
218 liftBase $ modifyMVar_ var $
219 pure . (r_state . at ngramsType %~ (Just . f . something))
222 f :: Map NodeId NgramsTableMap -> Map NodeId NgramsTableMap
223 f m = m & at dstListId %~ insertNewOnly (m ^. at srcListId)
225 -- TODO refactor with putListNgrams
226 -- The list must be non-empty!
227 -- The added ngrams must be non-existent!
228 addListNgrams :: RepoCmdM env err m
229 => NodeId -> NgramsType
230 -> [NgramsElement] -> m ()
231 addListNgrams listId ngramsType nes = do
233 liftBase $ modifyMVar_ var $
234 pure . (r_state . at ngramsType . _Just . at listId . _Just <>~ m)
237 m = Map.fromList $ (\n -> (n ^. ne_ngrams, n)) <$> nes
240 -- | TODO: incr the Version number
241 -- && should use patch
244 setListNgrams :: HasNodeStory env err m
246 -> TableNgrams.NgramsType
247 -> Map NgramsTerm NgramsRepoElement
249 setListNgrams listId ngramsType ns = do
250 printDebug "[setListNgrams]" (listId, ngramsType)
251 getter <- view hasNodeStory
252 var <- liftBase $ (getter ^. nse_getter) [listId]
253 liftBase $ modifyMVar_ var $
263 currentVersion :: HasNodeStory env err m
264 => ListId -> m Version
265 currentVersion listId = do
266 nls <- getRepo' [listId]
267 pure $ nls ^. unNodeStory . at listId . _Just . a_version
270 newNgramsFromNgramsStatePatch :: NgramsStatePatch' -> [Ngrams]
271 newNgramsFromNgramsStatePatch p =
272 [ text2ngrams (unNgramsTerm n)
273 | (n,np) <- p ^.. _PatchMap
274 -- . each . _PatchMap
275 . each . _NgramsTablePatch
276 . _PatchMap . ifolded . withIndex
277 , _ <- np ^.. patch_new . _Just
283 commitStatePatch :: HasNodeStory env err m
285 -> Versioned NgramsStatePatch'
286 -> m (Versioned NgramsStatePatch')
287 commitStatePatch listId (Versioned p_version p) = do
288 printDebug "[commitStatePatch]" listId
289 var <- getNodeStoryVar [listId]
290 vq' <- liftBase $ modifyMVar var $ \ns -> do
292 a = ns ^. unNodeStory . at listId . _Just
293 q = mconcat $ take (a ^. a_version - p_version) (a ^. a_history)
294 (p', q') = transformWith ngramsStatePatchConflictResolution p q
295 a' = a & a_version +~ 1
297 & a_history %~ (p' :)
300 -- Ideally we would like to check these properties. However:
301 -- * They should be checked only to debug the code. The client data
302 -- should be able to trigger these.
303 -- * What kind of error should they throw (we are in IO here)?
304 -- * Should we keep modifyMVar?
305 -- * Should we throw the validation in an Exception, catch it around
306 -- modifyMVar and throw it back as an Error?
307 assertValid $ transformable p q
308 assertValid $ applicable p' (r ^. r_state)
310 printDebug "[commitStatePatch] a version" (a ^. a_version)
311 printDebug "[commitStatePatch] a' version" (a' ^. a_version)
312 pure ( ns & unNodeStory . at listId .~ (Just a')
313 , Versioned (a' ^. a_version) q'
317 _ <- insertNgrams (newNgramsFromNgramsStatePatch p)
323 -- This is a special case of tableNgramsPut where the input patch is empty.
324 tableNgramsPull :: HasNodeStory env err m
326 -> TableNgrams.NgramsType
328 -> m (Versioned NgramsTablePatch)
329 tableNgramsPull listId ngramsType p_version = do
330 printDebug "[tableNgramsPull]" (listId, ngramsType)
331 var <- getNodeStoryVar [listId]
332 r <- liftBase $ readMVar var
335 a = r ^. unNodeStory . at listId . _Just
336 q = mconcat $ take (a ^. a_version - p_version) (a ^. a_history)
337 q_table = q ^. _PatchMap . at ngramsType . _Just
339 pure (Versioned (a ^. a_version) q_table)
344 -- tableNgramsPut :: (HasInvalidError err, RepoCmdM env err m)
345 -- Apply the given patch to the DB and returns the patch to be applied on the
348 tableNgramsPut :: ( HasNodeStory env err m
349 , HasInvalidError err
354 -> Versioned NgramsTablePatch
355 -> m (Versioned NgramsTablePatch)
356 tableNgramsPut tabType listId (Versioned p_version p_table)
357 | p_table == mempty = do
358 printDebug "[tableNgramsPut]" ("TableEmpty" :: Text)
359 let ngramsType = ngramsTypeFromTabType tabType
360 tableNgramsPull listId ngramsType p_version
363 printDebug "[tableNgramsPut]" ("TableNonEmpty" :: Text)
364 let ngramsType = ngramsTypeFromTabType tabType
365 (p, p_validity) = PM.singleton ngramsType p_table
367 assertValid p_validity
369 ret <- commitStatePatch listId (Versioned p_version p)
370 <&> v_data %~ (view (_PatchMap . at ngramsType . _Just))
376 tableNgramsPostChartsAsync :: ( HasNodeStory env err m
381 => UpdateTableNgramsCharts
384 tableNgramsPostChartsAsync utn logStatus = do
385 let tabType = utn ^. utn_tab_type
386 let listId = utn ^. utn_list_id
388 node <- getNode listId
389 let nId = node ^. node_id
390 _uId = node ^. node_user_id
391 mCId = node ^. node_parent_id
393 -- printDebug "[tableNgramsPostChartsAsync] tabType" tabType
394 -- printDebug "[tableNgramsPostChartsAsync] listId" listId
398 printDebug "[tableNgramsPostChartsAsync] can't update charts, no parent, nId" nId
399 pure $ jobLogFail $ jobLogInit 1
403 -- printDebug "[tableNgramsPostChartsAsync] Authors, updating Pie, cId" cId
404 (logRef, logRefSuccess, getRef) <- runJobLog 1 logStatus
406 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
411 -- printDebug "[tableNgramsPostChartsAsync] Institutes, updating Tree, cId" cId
412 -- printDebug "[tableNgramsPostChartsAsync] updating tree StopTerm, cId" cId
413 (logRef, logRefSuccess, getRef) <- runJobLog 3 logStatus
415 _ <- Metrics.updateTree cId (Just listId) tabType StopTerm
416 -- printDebug "[tableNgramsPostChartsAsync] updating tree CandidateTerm, cId" cId
418 _ <- Metrics.updateTree cId (Just listId) tabType CandidateTerm
419 -- printDebug "[tableNgramsPostChartsAsync] updating tree MapTerm, cId" cId
421 _ <- Metrics.updateTree cId (Just listId) tabType MapTerm
426 -- printDebug "[tableNgramsPostChartsAsync] Sources, updating chart, cId" cId
427 (logRef, logRefSuccess, getRef) <- runJobLog 1 logStatus
429 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
434 -- printDebug "[tableNgramsPostChartsAsync] Terms, updating Metrics (Histo), cId" cId
435 (logRef, logRefSuccess, getRef) <- runJobLog 6 logStatus
438 _ <- Metrics.updateChart cId (Just listId) tabType Nothing
440 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
442 _ <- Metrics.updateScatter cId (Just listId) tabType Nothing
444 _ <- Metrics.updateTree cId (Just listId) tabType StopTerm
446 _ <- Metrics.updateTree cId (Just listId) tabType CandidateTerm
448 _ <- Metrics.updateTree cId (Just listId) tabType MapTerm
454 printDebug "[tableNgramsPostChartsAsync] no update for tabType = " tabType
455 pure $ jobLogFail $ jobLogInit 1
458 { _ne_list :: ListType
459 If we merge the parents/children we can potentially create cycles!
460 , _ne_parent :: Maybe NgramsTerm
461 , _ne_children :: MSet NgramsTerm
465 getNgramsTableMap :: HasNodeStory env err m
467 -> TableNgrams.NgramsType
468 -> m (Versioned NgramsTableMap)
469 getNgramsTableMap nodeId ngramsType = do
470 v <- getNodeStoryVar [nodeId]
471 repo <- liftBase $ readMVar v
472 pure $ Versioned (repo ^. unNodeStory . at nodeId . _Just . a_version)
473 (repo ^. unNodeStory . at nodeId . _Just . a_state . at ngramsType . _Just)
476 dumpJsonTableMap :: HasNodeStory env err m
479 -> TableNgrams.NgramsType
481 dumpJsonTableMap fpath nodeId ngramsType = do
482 m <- getNgramsTableMap nodeId ngramsType
483 liftBase $ DTL.writeFile (unpack fpath) (DAT.encodeToLazyText m)
490 -- | TODO Errors management
491 -- TODO: polymorphic for Annuaire or Corpus or ...
492 -- | Table of Ngrams is a ListNgrams formatted (sorted and/or cut).
493 -- TODO: should take only one ListId
496 getTableNgrams :: forall env err m.
497 (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
498 => NodeType -> NodeId -> TabType
499 -> ListId -> Limit -> Maybe Offset
501 -> Maybe MinSize -> Maybe MaxSize
503 -> (NgramsTerm -> Bool)
504 -> m (VersionedWithCount NgramsTable)
505 getTableNgrams _nType nId tabType listId limit_ offset
506 listType minSize maxSize orderBy searchQuery = do
509 -- lIds <- selectNodesWithUsername NodeList userMaster
511 ngramsType = ngramsTypeFromTabType tabType
512 offset' = maybe 0 identity offset
513 listType' = maybe (const True) (==) listType
514 minSize' = maybe (const True) (<=) minSize
515 maxSize' = maybe (const True) (>=) maxSize
517 selected_node n = minSize' s
519 && searchQuery (n ^. ne_ngrams)
520 && listType' (n ^. ne_list)
524 selected_inner roots n = maybe False (`Set.member` roots) (n ^. ne_root)
526 ---------------------------------------
527 sortOnOrder Nothing = identity
528 sortOnOrder (Just TermAsc) = List.sortOn $ view ne_ngrams
529 sortOnOrder (Just TermDesc) = List.sortOn $ Down . view ne_ngrams
530 sortOnOrder (Just ScoreAsc) = List.sortOn $ view ne_occurrences
531 sortOnOrder (Just ScoreDesc) = List.sortOn $ Down . view ne_occurrences
533 ---------------------------------------
535 filteredNodes :: Map NgramsTerm NgramsElement -> [NgramsElement]
536 filteredNodes tableMap = rootOf <$> list & filter selected_node
538 rootOf ne = maybe ne (\r -> fromMaybe (panic "getTableNgrams: invalid root")
542 list = tableMap ^.. each
544 ---------------------------------------
545 selectAndPaginate :: Map NgramsTerm NgramsElement -> [NgramsElement]
546 selectAndPaginate tableMap = roots <> inners
548 list = tableMap ^.. each
549 rootOf ne = maybe ne (\r -> fromMaybe (panic "getTableNgrams: invalid root")
553 selected_nodes = list & take limit_
555 . filter selected_node
556 . sortOnOrder orderBy
557 roots = rootOf <$> selected_nodes
558 rootsSet = Set.fromList (_ne_ngrams <$> roots)
559 inners = list & filter (selected_inner rootsSet)
561 ---------------------------------------
562 setScores :: forall t. Each t t NgramsElement NgramsElement => Bool -> t -> m t
563 setScores False table = pure table
564 setScores True table = do
565 let ngrams_terms = table ^.. each . ne_ngrams
567 occurrences <- getOccByNgramsOnlyFast' nId
572 liftBase $ hprint stderr
573 ("getTableNgrams/setScores #ngrams=" % int % " time=" % hasTime % "\n")
574 (length ngrams_terms) t1 t2
576 occurrences <- getOccByNgramsOnlySlow nType nId
582 setOcc ne = ne & ne_occurrences .~ sumOf (at (ne ^. ne_ngrams) . _Just) occurrences
584 pure $ table & each %~ setOcc
585 ---------------------------------------
587 -- lists <- catMaybes <$> listsWith userMaster
588 -- trace (show lists) $
589 -- getNgramsTableMap ({-lists <>-} listIds) ngramsType
592 let scoresNeeded = needsScores orderBy
593 tableMap1 <- getNgramsTableMap listId ngramsType
595 tableMap2 <- tableMap1 & v_data %%~ setScores scoresNeeded
596 . Map.mapWithKey ngramsElementFromRepo
598 fltr <- tableMap2 & v_data %%~ fmap NgramsTable . setScores (not scoresNeeded)
600 let fltrCount = length $ fltr ^. v_data . _NgramsTable
603 tableMap3 <- tableMap2 & v_data %%~ fmap NgramsTable
604 . setScores (not scoresNeeded)
607 liftBase $ hprint stderr
608 ("getTableNgrams total=" % hasTime
612 % " sql=" % (if scoresNeeded then "map2" else "map3")
614 ) t0 t3 t0 t1 t1 t2 t2 t3
615 pure $ toVersionedWithCount fltrCount tableMap3
619 scoresRecomputeTableNgrams :: forall env err m.
620 (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
621 => NodeId -> TabType -> ListId -> m Int
622 scoresRecomputeTableNgrams nId tabType listId = do
623 tableMap <- getNgramsTableMap listId ngramsType
624 _ <- tableMap & v_data %%~ setScores
625 . Map.mapWithKey ngramsElementFromRepo
629 ngramsType = ngramsTypeFromTabType tabType
631 setScores :: forall t. Each t t NgramsElement NgramsElement => t -> m t
633 let ngrams_terms = table ^.. each . ne_ngrams
634 occurrences <- getOccByNgramsOnlyFast' nId
639 setOcc ne = ne & ne_occurrences .~ sumOf (at (ne ^. ne_ngrams) . _Just) occurrences
641 pure $ table & each %~ setOcc
648 -- TODO: find a better place for the code above, All APIs stay here
650 data OrderBy = TermAsc | TermDesc | ScoreAsc | ScoreDesc
651 deriving (Generic, Enum, Bounded, Read, Show)
653 instance FromHttpApiData OrderBy
655 parseUrlPiece "TermAsc" = pure TermAsc
656 parseUrlPiece "TermDesc" = pure TermDesc
657 parseUrlPiece "ScoreAsc" = pure ScoreAsc
658 parseUrlPiece "ScoreDesc" = pure ScoreDesc
659 parseUrlPiece _ = Left "Unexpected value of OrderBy"
662 instance ToParamSchema OrderBy
663 instance FromJSON OrderBy
664 instance ToJSON OrderBy
665 instance ToSchema OrderBy
666 instance Arbitrary OrderBy
668 arbitrary = elements [minBound..maxBound]
670 needsScores :: Maybe OrderBy -> Bool
671 needsScores (Just ScoreAsc) = True
672 needsScores (Just ScoreDesc) = True
673 needsScores _ = False
675 type TableNgramsApiGet = Summary " Table Ngrams API Get"
676 :> QueryParamR "ngramsType" TabType
677 :> QueryParamR "list" ListId
678 :> QueryParamR "limit" Limit
679 :> QueryParam "offset" Offset
680 :> QueryParam "listType" ListType
681 :> QueryParam "minTermSize" MinSize
682 :> QueryParam "maxTermSize" MaxSize
683 :> QueryParam "orderBy" OrderBy
684 :> QueryParam "search" Text
685 :> Get '[JSON] (VersionedWithCount NgramsTable)
687 type TableNgramsApiPut = Summary " Table Ngrams API Change"
688 :> QueryParamR "ngramsType" TabType
689 :> QueryParamR "list" ListId
690 :> ReqBody '[JSON] (Versioned NgramsTablePatch)
691 :> Put '[JSON] (Versioned NgramsTablePatch)
693 type RecomputeScoresNgramsApiGet = Summary " Recompute scores for ngrams table"
694 :> QueryParamR "ngramsType" TabType
695 :> QueryParamR "list" ListId
696 :> "recompute" :> Post '[JSON] Int
698 type TableNgramsApiGetVersion = Summary " Table Ngrams API Get Version"
699 :> QueryParamR "ngramsType" TabType
700 :> QueryParamR "list" ListId
701 :> Get '[JSON] Version
703 type TableNgramsApi = TableNgramsApiGet
704 :<|> TableNgramsApiPut
705 :<|> RecomputeScoresNgramsApiGet
706 :<|> "version" :> TableNgramsApiGetVersion
707 :<|> TableNgramsAsyncApi
709 type TableNgramsAsyncApi = Summary "Table Ngrams Async API"
713 :> AsyncJobs JobLog '[JSON] UpdateTableNgramsCharts JobLog
715 getTableNgramsCorpus :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
722 -> Maybe MinSize -> Maybe MaxSize
724 -> Maybe Text -- full text search
725 -> m (VersionedWithCount NgramsTable)
726 getTableNgramsCorpus nId tabType listId limit_ offset listType minSize maxSize orderBy mt =
727 getTableNgrams NodeCorpus nId tabType listId limit_ offset listType minSize maxSize orderBy searchQuery
729 searchQuery (NgramsTerm nt) = maybe (const True) isInfixOf mt nt
733 getTableNgramsVersion :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
738 getTableNgramsVersion _nId _tabType listId = currentVersion listId
743 -- Versioned { _v_version = v } <- getTableNgramsCorpus nId tabType listId 100000 Nothing Nothing Nothing Nothing Nothing Nothing
744 -- This line above looks like a waste of computation to finally get only the version.
745 -- See the comment about listNgramsChangedSince.
748 -- | Text search is deactivated for now for ngrams by doc only
749 getTableNgramsDoc :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
751 -> ListId -> Limit -> Maybe Offset
753 -> Maybe MinSize -> Maybe MaxSize
755 -> Maybe Text -- full text search
756 -> m (VersionedWithCount NgramsTable)
757 getTableNgramsDoc dId tabType listId limit_ offset listType minSize maxSize orderBy _mt = do
758 ns <- selectNodesWithUsername NodeList userMaster
759 let ngramsType = ngramsTypeFromTabType tabType
760 ngs <- selectNgramsByDoc (ns <> [listId]) dId ngramsType
761 let searchQuery (NgramsTerm nt) = flip S.member (S.fromList ngs) nt
762 getTableNgrams NodeDocument dId tabType listId limit_ offset listType minSize maxSize orderBy searchQuery
766 apiNgramsTableCorpus :: ( GargServerC env err m
768 => NodeId -> ServerT TableNgramsApi m
769 apiNgramsTableCorpus cId = getTableNgramsCorpus cId
771 :<|> scoresRecomputeTableNgrams cId
772 :<|> getTableNgramsVersion cId
773 :<|> apiNgramsAsync cId
775 apiNgramsTableDoc :: ( GargServerC env err m
777 => DocId -> ServerT TableNgramsApi m
778 apiNgramsTableDoc dId = getTableNgramsDoc dId
780 :<|> scoresRecomputeTableNgrams dId
781 :<|> getTableNgramsVersion dId
782 :<|> apiNgramsAsync dId
784 apiNgramsAsync :: NodeId -> GargServer TableNgramsAsyncApi
785 apiNgramsAsync _dId =
787 JobFunction $ \i log ->
790 printDebug "tableNgramsPostChartsAsync" x
792 in tableNgramsPostChartsAsync i log'
794 -- Did the given list of ngrams changed since the given version?
795 -- The returned value is versioned boolean value, meaning that one always retrieve the
797 -- If the given version is negative then one simply receive the latest version and True.
798 -- Using this function is more precise than simply comparing the latest version number
799 -- with the local version number. Indeed there might be no change to this particular list
800 -- and still the version number has changed because of other lists.
802 -- Here the added value is to make a compromise between precision, computation, and bandwidth:
803 -- * currentVersion: good computation, good bandwidth, bad precision.
804 -- * listNgramsChangedSince: good precision, good bandwidth, bad computation.
805 -- * tableNgramsPull: good precision, good bandwidth (if you use the received data!), bad computation.
806 listNgramsChangedSince :: HasNodeStory env err m
807 => ListId -> TableNgrams.NgramsType -> Version -> m (Versioned Bool)
808 listNgramsChangedSince listId ngramsType version
810 Versioned <$> currentVersion listId <*> pure True
812 tableNgramsPull listId ngramsType version & mapped . v_data %~ (== mempty)