Solrnet can't get mapping to work - solr

I am using VS2012, .NET 4.5 and SolrNet. I am struggling with solrnet mappings. I've succesfully started Apache Solr with jetty on http://localhost:8983/solr. My class which I want to add to solr is:
public class Register
{
[SolrUniqueKey("id")]
public string Id { get; set; }
[SolrField("body")]
public string Body { get; set; }
}
I succesfully connect to solr, but I can't put my document into it:
Startup.Init<Register>(solrAddress);
Solr = ServiceLocator.Current.GetInstance<ISolrOperations<Register>>();
var reg = new Register
{
Id = "SP2514N",
Body = #"Dosel je prosel"
};
Solr.Add(reg);
Solr.Commit();
Here I receive error, that 'body' is unknown field. I've also used MappingManager, like this:
var mgr = new MappingManager();
var property = typeof(Register).GetProperty("Id");
mgr.Add(property, "id");
mgr.SetUniqueKey(property);
mgr.Add(typeof(Register).GetProperty("Body"), "body");
But, again, my field was not mapped. What am I doing wrong? Isn't the mapping to solr supposed to be done through code? Do I need a special xml file?

You need to confirm that you have a body field defined in your schema. If you are just using the default schema that comes with Solr, it does not include a body field. You can copy an existing similar entry in the schema.xml file, like description to get you going.
For more reference on configuring the Solr schema please refer to the following:
Solr Reference Guide - Overview of Documents, Fields and Schema Design
schema.xml - SolrTutorial.com

Related

Dapper.Contrib: How to get a row by filtering on column other than ID?

My class is like below:
[Table("tblUser")]
public class User
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
}
Using Dapper.Contrib, is there a way to get the User record by Title instead of Id?
If I query like below, it works. But, I want to filter on Title column which is not a key.
await connection.GetAsync<User>(Id);
Looking at the documentation, Dapper.Contrib does not support retrieval of records using criteria other than key. In other words, it does not support any kind of predicate system in its current implementation.
Using GetAll, you can further filter it with linq. But remember that this is not being executed on RDBMS. It will be executed on application side or in memory. That means, entire data will be loaded first and then it will be filtered.
Personally, I will choose to use Dapper (bypassing Contrib) for such specific scenario. Other part of the project will still use Contrib.

How do I access the explain() method and executionStats when using Spring Data MongoDb v2.x?

It's time to ask the community. I cannot find the answer anywhere.
I want to create a generic method that can trace all my repository queries and warn me if a query is not optimized (aka missing an index).
With Spring Data MongoDb v2.x and higher and with the introduction of the Document API, I cannot figure out how to access DBCursor and the explain() method.
The old way was to do it like this:
https://enesaltinkaya.com/java/how-to-explain-a-mongodb-query-in-spring/
Any advise on this is appreciated.
I know this is an old question but wanted to give input from a similar requirement I had in capacity planning for a cosmos Db project using Java Mongo API driver v2.X.
Summarizing Enes Altınkaya's blog post. With an #autowired MongoTemplate we use runCommand to execute server-side db queries by passing a Document object. Getting to an explain output we parse a Query or Aggregate object into a new Document object and add the entry {"executionStats": true}(or {"executionStatistics": true} for cosmos Db). Then wrap it in an another Document using "explain" as the propery.
For Example:
Query:
public static Document documentRequestStatsQuery(MongoTemplate mongoTemplate,
Query query, String collectionName) {
Document queryDocument = new Document();
queryDocument.put("find", collectionName);
queryDocument.put("filter", query.getQueryObject());
queryDocument.put("sort", query.getSortObject());
queryDocument.put("skip", query.getSkip());
queryDocument.put("limit", query.getLimit());
queryDocument.put("executionStatistics", true);
Document command = new Document();
command.put("explain", queryDocument);
Document explainResult = mongoTemplate.getDb().runCommand(command);
return explainResult;
}
Aggregate:
public static Document documentRequestStatsAggregate(MongoTemplate mongoTemplate,
Aggregation aggregate, String collection) {
Document explainAggDocument = Document.parse(aggregate.toString());
explainAggDocument.put("aggregate", collection);
explainAggDocument.put("executionStatistics", true);
Document command = new Document();
command.put("explain", explainAggDocument);
Document explainResult = mongoTemplate.getDb().runCommand(command);
return explainResult;
}
For the actual monitoring, since Service & Repository classes are MongoTemplate abstractions we can use Aspects to capture the query/aggregate execution details as the applications is running.
For Example:
#Aspect
#Component
#Slf4j
public class RequestStats {
#Autowired
MongoTemplate mongoTemplate;
#After("execution(* org.springframework.data.mongodb.core.MongoTemplate.aggregate(..))")
public void logTemplateAggregate(JoinPoint joinPoint) {
Object[] signatureArgs = joinPoint.getArgs();
Aggregation aggregate = (Aggregation) signatureArgs[0];
String collectionName = (String) signatureArgs[1];
Document explainAggDocument = Document.parse(aggregate.toString());
explainAggDocument.put("aggregate", collectionName);
explainAggDocument.put("executionStatistics", true);
Document dbCommand = new Document();
dbCommand.put("explain", explainAggDocument);
Document explainResult = mongoTemplate.getDb().runCommand(dbCommand);
log.info(explainResult.toJson());
}
}
Outputs something like below after each execution:
{
"queryMetrics": {
"retrievedDocumentCount": 101,
"retrievedDocumentSizeBytes": 202214,
"outputDocumentCount": 101,
"outputDocumentSizeBytes": 27800,
"indexHitRatio": 1.0,
"totalQueryExecutionTimeMS": 15.85,
"queryPreparationTimes": {
"queryCompilationTimeMS": 0.21,
"logicalPlanBuildTimeMS": 0.5,
"physicalPlanBuildTimeMS": 0.58,
"queryOptimizationTimeMS": 0.1
},
"indexLookupTimeMS": 10.43,
"documentLoadTimeMS": 0.93,
"vmExecutionTimeMS": 13.6,
"runtimeExecutionTimes": {
"queryEngineExecutionTimeMS": 1.56,
"systemFunctionExecutionTimeMS": 1.36,
"userDefinedFunctionExecutionTimeMS": 0
},
"documentWriteTimeMS": 0.68
}
// ...
I usually log this out into another collection or write to file.

Azure Search API/SDK Analyzer Attribute Alternative

I am setting up my Azure Search index using the API/SDK attributes. But I want to be able to change the Analyzer for a specific index based on an app setting (i.e. User sets language to French, so this index will use the French Analyzer).
Example of a couple of my index properties
[IsSearchable]
[Analyzer(AnalyzerName.AsString.EnMicrosoft)]
public string Title { get; set; }
[IsSearchable]
[Analyzer(AnalyzerName.AsString.EnMicrosoft)]
public string Description { get; set; }
I am setting the Analyzer to the Microsoft English one. But let's say I want to create another index, but this time using the Microsoft French Analyzer.
Is there a way to programmatically set this, apart from using an attribute? Some sort of event? OnIndexCreating etc... As it's restricting for more complex apps.
I can't have a separate field for each language either as I don't know what languages the user might choose.
Any help appreciated.
Once your Index instance is created from a model class, you can access the list of Fields and change their properties, the Analyzer is one of them.
var index = new Index()
{
Name = "myindex",
Fields = FieldBuilder.BuildForType<MyModel>()
};
Field field = index.Fields.First(f => f.Name == "Title");
field.Analyzer = "fr.microsoft"; // There is an implicit conversion from string to AnalyzerName.
Alternatively, you can just build the Field instances yourself:
var index = new Index()
{
Name = "myindex",
Fields = new List<Field>()
{
new Field("Title", DataType.String, "fr.microsoft"),
new Field("Description", DataType.String, "fr.microsoft")
}
}
In both cases you can use a string for the analyzer name, which you could receive as user input or from config.

How to index general link field

I would like to know how Solr indexes general link field or do we need to create computed index field for this ?
I have a helper class which is inheriting from SearchResultItem and it has below index field.
[IndexField("Call To Action")]
public LinkField CallToAction { get; set; }
This field is a general link field in sitecore.
Below is the search code which retrieves all the Event_card values except CallToAction (i.e. Always null). if I convert the field type from Link to string , I get the entire general link raw value which is difficult to parse at view and make it editable through glass mapper.
if (result.TotalSearchResults != 0)
{
//Load Event card data to be displayed on page
var resultItems =
result.Select(c => new Event_Card
{
Headline = c.Document.Headline,
Start_Date=c.Document.StartDate,
Content=c.Document.ContentData,
Call_To_Action=c.Document.CallToAction // this is always null
});
}
Here is my Entity class related to Event_Card
Event_Card
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(IEvent_CardConstants.Call_To_ActionFieldName)]
public virtual Link Call_To_Action { get; set; }
IEvent_Card
[SitecoreField(IEvent_CardConstants.Call_To_ActionFieldName)]
Link Call_To_Action { get; set; }
public static partial class IEvent_CardConstants
{
public static readonly ID Call_To_ActionFieldId = new ID("4c296a05-d05f-47c5-8934-8801bec5be85");
public const string Call_To_ActionFieldName = "Call To Action";
}
Can anybody let me know How can I achieve this. If we need to use computed field , an example would be of great help.
Thanks in Advance !
I just quickly browsed and found useful link for you.
Map sitecore 8 general link field from Index
I think this Stack overflow question describes what you are saying and there is a link which might be helpful to you.

SolrJ nested documents

I have is this:
public class Product {
#Field("object_id")
private String objectId;
private List<MyObject> listOfMyObjects;
}
I use SolrJ to save the info. How can I make listOfMyObjects look like list of nested documents in Solr response. I can make the field multivalued, but I need the list to be list of documents.
I can see that this question is asked few times(e.g. Solrj Block Join Bean support ) but no answer. Solr supports nested documents, but how to make it happen using SolrJ with annotations and schema.xml.

Resources