Liferay searchContext search by AssetTags and Keywords - search

I'm trying to implement custom search portlet through AssetEntries. Currently AssetEntryQuery doesn't allow to search with keywords. I'm trying to search through FacetedSearcher. Search by keywords seems to be ok. But when I'm trying to search by AssetTagNames
searchContext.setAssetTagNames(assetTagNames)
it doesn't work at all.
Here's my piece of code
SearchContext searchContext = new SearchContext();
Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
assetEntriesFacet.setStatic(true);
searchContext.addFacet(assetEntriesFacet);
/*MultiValueFacet multiValueFacet=new MultiValueFacet(searchContext);
multiValueFacet.setFieldName("assetTagNames");
multiValueFacet.setStatic(false);
searchContext.addFacet(multiValueFacet);*/
searchContext.setCompanyId(themeDisplay.getCompanyId());
String []assetTagNames=new String[1];
assetTagNames[0]= assetTagName;
searchContext.setAssetTagNames(assetTagNames);
searchContext.setKeywords(keywords);
String[] entryClassName = {JournalArticle.class.getName()};
searchContext.setEntryClassNames(entryClassName);
Indexer indexer = FacetedSearcher.getInstance();
// searchContext.setAndSearch(true);
Hits hits = indexer.search(searchContext);
System.out.println("Hits: " + hits.getLength());
Resulted query for request
searchKeyword: key1key1
assetTagName: sometag
+(+(companyId:1) +((+(entryClassName:com.liferay.portlet.journal.model.JournalArticle) +(status:0)))) +(assetCategoryTitles:*key1key1* assetCategoryTitles_en_US:*key1key1* assetTagNames:*key1key1* comments:key1key1 content:key1key1 description:key1key1 properties:key1key1 title:key1key1 url:key1key1 userName:*key1key1* classPK:key1key1 content_en_US:key1key1 description_en_US:key1key1 entryClassPK:key1key1 title_en_US:key1key1 type:key1key1)
As you see AssetTag isn't applied to the query.
I've already tried to set it through
searchContext.setAttribute("assetTagNames",assetTagName);
and commented MultiValueFacet code but wih no result.
For further i need to search by dateRange and Categories. Has anybody any idea?

Fortunately solved this.
If you'd like to search through tags you've to use a separate facet for this, e.g.
MultiValueFacet assetTagsFacet = new MultiValueFacet(searchContext);
assetTagsFacet.setFieldName(Field.ASSET_TAG_NAMES);
searchContext.addFacet(assetTagsFacet);
Also use searchContext.setAttribute("assetTagNames", assetTagName); instead of searchContext.setAssetTagNames(assetTagName);
For searching through Categories the same thing:
MultiValueFacet assetCategoriesFacet = new MultiValueFacet(searchContext);
assetCategoriesFacet.setFieldName("assetCategoryTitles");
searchContext.addFacet(assetCategoriesFacet);
searchContext.setAttribute("assetCategoryTitles", assetCategoryName);
Also i wanted to search by custom type of JournalArticle, Ive created facet for this, but got "type" twice in query. As a solution i used MultiValueFacet instead of AssetEntriesFacet during setting entryClassName
MultiValueFacet assetEntriesFacet = new MultiValueFacet(searchContext);
assetEntriesFacet.setFieldName("entryClassName");
searchContext.setAttribute("entryClassName",JournalArticle.class.getName());
searchContext.addFacet(assetEntriesFacet);

Related

Search in new Sitecore ContentSearch using whole words

I am using new Sitecore search, and the issue I ran into is having results come for words that have nothing to do with my search term.
For example, searching for "lies" will find "applies". And this is not what I am looking for.
This is an example of search I am doing (simplified). It is a direct LINQ check for "Contains" on the "Content" property of the SearchResultItem, and most likely not what I supposed to do. It is just happen to be that samples I find online are practically doing so.
Example of my code (simplified). In here I break down the search sentence to separate keywords. By the way, I am looking for a way to show full sentence match first.
using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
{
var results = context.GetQueryable<SearchResultItem>()
.Filter(i => i.Path.StartsWith(Home.Paths.FullPath))
.Filter(GetTermPredicate(Term));
// use results here
}
protected Expression<Func<SearchResultItem, bool>> GetTermPredicate(string term)
{
var predicate = PredicateBuilder.True<SearchResultItem>();
foreach (var tempTerm in term.Split(' '))
{
predicate = predicate.And(p => p.Content.Contains(tempTerm));
}
return predicate;
}
Thank you in advance!!
All right. I got help from Sitecore Support.
In my version of Sitecore I can use the following to acheive search for a whole word instead of partial:
instead of:
predicate = predicate.And(p => p.Content.Contains(tempTerm));
use
predicate = predicate.And(p => p.Content.Equals(tempTerm));
Issue solved.
Replace Filter in your code by Where, it should be fine,
here is an example :
var currentIndex = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = currentIndex.CreateSearchContext())
{
var predicate = PredicateBuilder.True();
foreach (var currentWord in term.Split(‘ ‘))
{
predicate = predicate.Or(x => x.Content.Contains(currentWord ));
}
var results = context.GetQueryable().Where(predicate).GetResults();
}
As Ahmed notes, you should use Where instead of Filter, since Filter has no effect on search rank. The classic use case for filters is to apply a facet chosen by the user without distorting the ordering of results, as would happen if you used a Where clause.
Filtering is similar to using Where to restrict the result list. Both methods will affect the result in the same
result list, but when you use a Filter the scoring/ranking of the search hits is not affected by the filters.
Developer's Guide to Item Buckets and Search
There's a good dicussion of when to use Filter on the Sitecore 7 team blog:
Making Good Part 4: Filters, Paging and I'm feeling lucky.
If you only want to search for whole words, you could prefix and postfix the searchterm with a space. Allthough this doesn't catch all situations.

Trouble in search in grocery CRUD, search by one field with no results

Trouble in search in grocery CRUD, search by one field with no results , then I cannot get the original results back, "clear filtering" does not work, and refresh page will auto hide all results. Thanks!
Here is my code:
$crud = new grocery_CRUD();
$crud->set_table('p_user');
$crud->where('parentid', $parent_id);
$crud->required_fields('name');
$crud->columns('name','password','email','type');
$output = $crud->render();
Screenshot:
I think your problem is the code:
$crud->where('parentid', $parent_id);
Did you include the $parent_id to the URL? So for example if you have
http://www.example.com/main/test
it has to be: http://www.example.com/main/test/345 or something like that. So in your case I think this will solve your problem:
if (!empty($parent_id)) {
$crud->where('parentid', $parent_id);
}

How to display results of Smartsearch

I'm creating a webpart that uses the SearchHelper to get smart search results based on the search paramaters to display in a live search via Ajax.
I am looking for a way to display the results using the dataset that
SearchHelper.Search(SearchParameters)
returns in the same manner that the SearchResults webparts work.
Ok never mind, found the answer. The answer is to just use the BasicRepeater.
var results = SearchHelper.Search(sp);
BasicRepeater br = new BasicRepeater();
br.DataSource = results;
br.ItemTemplate = CMSDataProperties.LoadTransformation(this, CMS.Root.SmartSearchResults", false);

Search query with Subsonic

Ok,
Today I am trying to learn Subsonic. Pretty cool stuff.
I am trying to build some search functionality into my website but am struggling about how I might achieve this in Subsonic.
I have one search field that could contain multiple keywords. I want to return results that match all of the keywords. The target on the search is a single text column.
So far I have this (it runs but never returns results):
return new SubSonic.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(InfopathArchive.XmlDocColumn).Like(keywords)
.ExecuteTypedList<Visit>();
There is a one to one mapping between the Visit table and the InfoPathArchive table. I just want to return the collection of Visits that have the keywords in the related XMLDocColumn.
If I could get that working it would be great. Now the second problem is that if someone searches for 'australia processmodel' then obviously the above code should only return that exact phrase. How can I create a query that splits up my search term so that it must return documents that contain ALL of the individual search terms?
Any help appreciated.
Edit: Ok, so the basic search works, but the multiple keyword search doesnt. I did what Adam suggested but it seems Subsonic only uses one parameter for the query.
Here is the code:
List<string> wordsInQueryList = keywords.Split(' ').ToList();
SqlQuery q = Select.AllColumnsFrom<Visit>()
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(Visit.IsDeletedColumn).IsEqualTo(false);
foreach(string wordInQuery in wordsInQueryList)
{
q = q.And(InfopathArchive.XmlDocColumn).Like("%" + wordInQuery + "%");
}
return q.ExecuteTypedList();
Then if I look at the query that Subsonic generates:
SELECT (bunch of columns)
FROM [dbo].[Visit]
INNER JOIN [dbo].[InfopathArchive] ON [dbo].[Visit].[VisitId] = [dbo].[InfopathArchive].[VisitId]
WHERE [dbo].[Visit].[IsDeleted] = #IsDeleted
AND [dbo].[InfopathArchive].[XmlDoc] LIKE #XmlDoc
AND [dbo].[InfopathArchive].[XmlDoc] LIKE #XmlDoc
So it ends up that only the last keyword is being searched for.
Any ideas?
First question:
return new SubSonic.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(InfopathArchive.XmlDocColumn).Like("%" + keywords + "%")
.ExecuteTypedList<Visit>();
Second question:
Pass a List of words in your query to a function that builds a SubSonic query as follows
SqlQuery query = DB.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where("1=1");
foreach(string wordInQuery in wordsInQueryList)
{
query = query.And(InfopathArchive.XmlDocColumn).Like("%" + wordInQuery + "%")
}
return query.ExecuteTypedList<Visit>();
Obviously this is untested but it should point you in the right direction.
You can do what Adam is suggesting or with 2.2 you can simply use "Contains()" instead of Like("%...%"). We also support StartsWith and EndsWith() :)

Exact phrase search using Lucene.net

I am having trouble searching for an exact phrase using Lucene.NET 2.0.0.4
For example I am searching for "scope attribute sets the variable" (including quotes) but receive no matches, I have confirmed 100% that the phrase exists.
Can anyone suggest where I am going wrong? Is this even supported with Lucene.NET? As usual the API documentation is not too helpful and a few CodeProject articles I've read don't specifically touch on this.
Using the following code to create the index:
Directory dir = Lucene.Net.Store.FSDirectory.GetDirectory("Index", true);
Analyzer analyzer = new Lucene.Net.Analysis.SimpleAnalyzer();
IndexWriter indexWriter = new Lucene.Net.Index.IndexWriter(dir, analyzer,true);
//create a document, add in a single field
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
Lucene.Net.Documents.Field fldContent = new Lucene.Net.Documents.Field(
"content", File.ReadAllText(#"Documents\100.txt"),
Lucene.Net.Documents.Field.Store.YES,
Lucene.Net.Documents.Field.Index.TOKENIZED);
doc.Add(fldContent);
//write the document to the index
indexWriter.AddDocument(doc);
I then search for a phrase using:
//state the file location of the index
Directory dir = Lucene.Net.Store.FSDirectory.GetDirectory("Index", false);
//create an index searcher that will perform the search
IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
QueryParser qp = new QueryParser("content", new SimpleAnalyzer());
// txtSearch.Text Contains a phrase such as "this is a phrase"
Query q=qp.Parse(txtSearch.Text);
//execute the query
Lucene.Net.Search.Hits hits = searcher.Search(q);
The target document is about 7 MB plain text.
I have seen this previous question however I don't want a proximity search, just an exact phrase search.
Shashikant Kore is correct with his answer, you need to enable term positions...
However, I would recommend not storing the text of the document in the field unless you absolutely need it to return back to you in the search results... Setting the store to 'NO' might help reduce the size of your index a bit.
Lucene.Net.Documents.Field fldContent =
new Lucene.Net.Documents.Field("content",
File.ReadAllText(#"Documents\100.txt"),
Lucene.Net.Documents.Field.Store.NO,
Lucene.Net.Documents.Field.Index.TOKENIZED,
Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS);
You have not enabled the term positions. Creating field as follows should solve your problem.
Lucene.Net.Documents.Field fldContent =
new Lucene.Net.Documents.Field("content",
File.ReadAllText(#"Documents\100.txt"),
Lucene.Net.Documents.Field.Store.YES,
Lucene.Net.Documents.Field.Index.TOKENIZED,
Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS);

Resources