/// <summary> /// Subset (words and occurences etc.) creator /// </summary> /// <param name="indexName">the name of the index</param> /// <param name="textFields">the text field where the words and occurences come from, the fields where you have the analyzer_1, analyzer_2...</param> /// <param name="interPretedFields">this will be used for the all word occurences only (where the tokencount tokenfilter is)</param> /// <param name="nGramCount"></param> /// <param name="queryFactory"></param> /// <param name="attachmentFields"></param> public SubsetCreator(string indexName, List <string> textFields, List <string> interPretedFields, int nGramCount, IQueryFactory queryFactory, List <string> attachmentFields) { this.attachmentFields = attachmentFields; this.queryFactory = queryFactory; _indexName = indexName; _textFields = textFields; _nGramCount = nGramCount; _allWordsOccurences = queryFactory.GetWordQuery(_indexName).GetAllWordsOccurences(interPretedFields, nGramCount); }
public Subset CreateByTag(string tagId, string tagField) { var docQuery = queryFactory.GetDocumentQuery(_indexName); var wordQuery = queryFactory.GetWordQuery(_indexName); var docs = docQuery.GetByTagId(tagId, tagField, DocumentQuery.GetDocumentElasticFields(new[] { DocumentElastic.IdField })); Func <string, bool> isAttachmentField = (field) => attachmentFields.Any(attachmentField => string.Equals(attachmentField, field, StringComparison.OrdinalIgnoreCase)); var fields = _textFields .Select(field => isAttachmentField(field) ? $"{field}.content" : field) .ToList(); var wwo = wordQuery.GetWordsWithOccurences(docs.Select(d => d.Id).ToList(), fields, _nGramCount); var subset = new Subset { AllWordsOccurencesSumInCorpus = _allWordsOccurences, AllWordsOccurencesSumInTag = wwo.Sum(w => w.Value.Tag), WordsWithOccurences = wwo }; return(subset); }
/// <summary> /// Gets the tags. /// </summary> /// <param name="withDetails">if set to <c>true</c> [with details].</param> /// <returns></returns> public List <Tag> GetTagModels(string dataSetName, bool withDetails) { var dataSet = DataSet(dataSetName).DataSet; var tags = new List <Tag>(); var tagElastics = TagQuery(dataSetName).GetAll().Items; var tagElasticsDic = tagElastics.ToDictionary(t => t.Id, t => t); var wordQuery = queryFactory.GetWordQuery(dataSet.Name); Dictionary <string, int> docCountDic = null; Dictionary <string, int> wordCountDic = null; if (withDetails) { docCountDic = DocumentQuery(dataSetName).CountForTags(tagElasticsDic.Keys.ToList(), dataSet.TagField); // the text field contains the concatenate word also, so we have to use the interpretedfields wordCountDic = wordQuery.CountForWord(dataSet.InterpretedFields.Select(Elastic.Queries.DocumentQuery.MapDocumentObjectName).ToList(), 1, tagElasticsDic.Keys.ToList(), Elastic.Queries.DocumentQuery.MapDocumentObjectName(dataSet.TagField)); } foreach (var tagId in tagElasticsDic.Keys) { var tagElastic = tagElasticsDic[tagId]; var pathItems = tagElasticsDic .Where(d => tagElastic.ParentIdList.Contains(d.Key)) .OrderBy(t => t.Value.Level) .Select(d => new PathItem { Id = d.Value.Id, Name = d.Value.Name, Level = d.Value.Level }) .ToList(); var wordCount = 0; var documentCount = 0; if (withDetails) { documentCount = docCountDic[tagId]; wordCount = wordCountDic[tagId]; } var tag = new Tag { Id = tagElastic.Id, Name = tagElastic.Name, ParentId = tagElastic.ParentId(), Properties = new TagProperties { Paths = pathItems, IsLeaf = tagElastic.IsLeaf, Level = tagElastic.Level, DocumentCount = documentCount, WordCount = wordCount } }; tags.Add(tag); } if (withDetails) { var tagIdsByLevel = TagHelper.GetTagIdsByLevel(tags, p => p.ParentId, i => i.Id); // Go leaf to root to add child document & word count to parent properties if (tagIdsByLevel.Keys.Count > 1) { for (int level = tagIdsByLevel.Keys.Count - 2; level > 0; level--) { foreach (var tagIdByLevel in tagIdsByLevel[level]) { var tag = tags.FirstOrDefault(t => t.Id == tagIdByLevel); if (tag == null) { continue; } var childTags = tags.Where(t => t.ParentId == tagIdByLevel).ToList(); tag.Properties.DocumentCount += childTags.Sum(t => t.Properties.DocumentCount); tag.Properties.WordCount += childTags.Sum(t => t.Properties.WordCount); } } } } return(tags); }
public IActionResult Recommend(string id, [FromBody] PrcRecommendationRequest request) { if (request == null) { return(new StatusCodeResult(StatusCodes.Status400BadRequest)); } // If Id is Alias, translate to Id if (GlobalStore.ServiceAliases.IsExist(id)) { id = GlobalStore.ServiceAliases.Get(id); } if (!GlobalStore.ActivatedPrcs.IsExist(id)) { return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest, string.Format(ServiceResources.ServiceNotExistsOrNotActivated, ServiceTypeEnum.Prc))); } if (!string.IsNullOrEmpty(request.TagId) && !GlobalStore.ActivatedPrcs.Get(id).PrcsSettings.Tags.Any(t => t.Id == request.TagId)) { return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest, ServiceResources.TheGivenTagIsMissingFromThePRCService)); } var globalStoreDataSet = GlobalStore.DataSets.Get(GlobalStore.ActivatedPrcs.Get(id).PrcsSettings.DataSetName); var dataSet = globalStoreDataSet.DataSet; var analyzeQuery = queryFactory.GetAnalyzeQuery(dataSet.Name); var tokens = analyzeQuery.Analyze(request.Text, 1).ToList(); var text = string.Join(" ", tokens); //tagId meghatározása var tagId = string.Empty; if (!string.IsNullOrEmpty(request.TagId)) { tagId = request.TagId; } else { //ha nincs megadva tagId akkor kiszámoljuk a prc scorer-ekkel var allResults = new List <KeyValuePair <string, double> >(); foreach (var scorerKvp in GlobalStore.ActivatedPrcs.Get(id).PrcScorers) { var score = scorerKvp.Value.GetScore(text, 1.7, true); allResults.Add(new KeyValuePair <string, double>(scorerKvp.Key, score)); } var resultsList = allResults.Where(r => r.Value > 0).OrderByDescending(r => r.Value).ToList(); if (resultsList.Count == 0) { return(new OkObjectResult(new List <PrcRecommendationResult>())); } tagId = resultsList.First().Key; } var tagsToTest = new List <string>(); if (request.Filter?.TagIdList?.Any() == true) { var existingTags = GlobalStore.ActivatedPrcs.Get(id).PrcsSettings.Tags.Select(t => t.Id).Intersect(request.Filter.TagIdList).ToList(); if (existingTags.Count < request.Filter.TagIdList.Count) { var missingTagIds = request.Filter.TagIdList.Except(existingTags).ToList(); return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest, string.Format(ServiceResources.TheFollowingTagIdsNotExistInTheDataSet_0, string.Join(", ", missingTagIds)))); } tagsToTest = request.Filter.TagIdList; } var globalSubset = GlobalStore.ActivatedPrcs.Get(id).PrcSubsets[tagId]; if (globalSubset.WordsWithOccurences == null) { return(new HttpStatusCodeWithErrorResult(StatusCodes.Status406NotAcceptable, ServiceResources.TheGivenTagHasNoWordsInDictionary)); } var wordsInDic = globalSubset.WordsWithOccurences.Keys.Intersect(tokens).ToList(); var baseSubset = new Cerebellum.Subset { AllWordsOccurencesSumInCorpus = globalSubset.AllWordsOccurencesSumInCorpus, AllWordsOccurencesSumInTag = globalSubset.AllWordsOccurencesSumInTag, WordsWithOccurences = wordsInDic.ToDictionary(w => w, w => globalSubset.WordsWithOccurences[w]) }; var baseDic = new Cerebellum.Dictionary.TwisterAlgorithm(baseSubset, true, false).GetDictionary(); var globalScorer = GlobalStore.ActivatedPrcs.Get(id).PrcScorers[tagId]; var baseScorer = new Cerebellum.Scorer.PeSScorer(new Dictionary <int, Dictionary <string, double> > { { 1, baseDic } }); var baseScore = baseScorer.GetScore(text, 1.7); var globalScore = globalScorer.GetScore(text, 1.7); var results = new List <PrcRecommendationResult>(); if (baseScore == 0 || globalScore == 0) { return(new OkObjectResult(results)); } var filterQuery = request.Filter?.Query?.Trim(); var query = string.IsNullOrEmpty(filterQuery) ? string.Empty : $"({filterQuery}) AND "; // '+ 1' because we give score between 0 and 1 but in elasticsearch that means negative boost query = string.Format("{0}({1})", query, string.Join(" ", baseDic.Select(k => $"{k.Key}^{k.Value + 1}"))); string shouldQuery = null; // weighting if (request.Weights?.Any() == true) { shouldQuery = string.Join(" ", request.Weights.Select(k => $"({k.Query})^{k.Value}")); } var fieldsForRecommendation = GlobalStore.ActivatedPrcs.Get(id).PrcsSettings.FieldsForRecommendation; var documentQuery = queryFactory.GetDocumentQuery(dataSet.Name); var documentElastics = new List <DocumentElastic>(); var scrollResult = documentQuery .Filter(query, tagsToTest, dataSet.TagField, request.Count, null, false, fieldsForRecommendation, globalStoreDataSet.DocumentFields, DocumentService.GetFieldFilter(globalStoreDataSet, new List <string> { request.NeedDocumentInResult ? "*" : globalStoreDataSet.DataSet.IdField }), null, null, null, shouldQuery); documentElastics.AddRange(scrollResult.Items); var docIdsWithScore = new ConcurrentDictionary <string, double>(new Dictionary <string, double>()); var wordQuery = queryFactory.GetWordQuery(dataSet.Name); Func <string, bool> isAttachmentField = (field) => globalStoreDataSet.AttachmentFields.Any(attachmentField => string.Equals(attachmentField, field, StringComparison.OrdinalIgnoreCase)); Parallel.ForEach(documentElastics, parallelService.ParallelOptions(), docElastic => { var fieldList = fieldsForRecommendation .Select(field => isAttachmentField(field) ? $"{field}.content" : field) .Select(DocumentQuery.MapDocumentObjectName) .ToList(); var wwo = wordQuery.GetWordsWithOccurences(new List <string> { docElastic.Id }, fieldList, 1); var actualCleanedText = string.Join(" ", wwo.Select(w => string.Join(" ", Enumerable.Repeat(w.Key, w.Value.Tag)))); var actualBaseScore = baseScorer.GetScore(actualCleanedText, 1.7); if (actualBaseScore == 0) { return; } var actualGlobalScore = globalScorer.GetScore(actualCleanedText, 1.7); if (actualGlobalScore == 0) { return; } var finalScore = (actualBaseScore / baseScore) / (actualGlobalScore / globalScore); docIdsWithScore.TryAdd(docElastic.Id, finalScore); }); var resultDic = docIdsWithScore.OrderByDescending(rd => rd.Value).ToList(); if (request.Count != 0 && resultDic.Count > request.Count) { resultDic = resultDic.Take(request.Count).ToList(); } var docsDic = request.NeedDocumentInResult ? resultDic.Select(r => documentElastics.First(d => d.Id == r.Key)).ToDictionary(d => d.Id, d => d) : null; return(new OkObjectResult(resultDic.Select(kvp => new PrcRecommendationResult { DocumentId = kvp.Key, Score = kvp.Value, Document = request.NeedDocumentInResult ? docsDic[kvp.Key].DocumentObject : null }))); }