I have the following LINQ for my task -
return IEnumerable<MyLDRObject> result = agreementLinesData.Zones
.Where(a => accessibleProductLine ==a.ProductLine)
.Where(b => b.Zone.Contains("CHEST") ||
b.Zone.Contains("COLLAR") ||
b.Zone.Contains("WAIST") ||
b.Zone.Contains("RLOWERARM") ||
b.Zone.Contains("LLOWERARM") ||
(isParticipantPregnant == true &&
b.Zone.Contains("FETAL")))
.OrderBy(a => a.Description)
.Select(a => new MyLDRObject { Key = a.Zone, DisplayName = a.Description });
How can I set a default value to be selected if isParticipantPregnant == true?
Thanks
Supratik
If I understood, you want to set a Default value to Key and/or DisplayName if the property isParticipantPregnant is true. If this is it, so all you need is a lambda expression in the select.
Select(a => new MyLDRObject {
Key = isParticipantPregnant ? "defValue" : a.Zone,
DisplayName = isParticipantPregnant ? "defValue" : a.Description
})
Related
let expectedKey = 'Student';
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
if(expectedKey === 'Student'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.studentCode);
}
if(expectedDKey === 'Department'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.departmentCode);
}
if(expectedKey === 'Paper'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.paperCode);
}
if(expectedKey === 'Results'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.resultsCode);
}
}
I don't want to use these many if blocks as there will more keys in the future. Instead, I have to pick the required value for studentCode, departmentCode, paperCode, or resultsCode from JSON based on expectedKey. Any help please?
You can access object properties by dot notation (foo.bar) or bracket notation (foo['bar']). In your case, you'll have to ensure expectedKey matches a valid key in your object with assertion before the cy commands.
let expectedKey = 'studentCode';
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
expect(appDetails, 'valid key').to.have.property(expectedKey)
cy.get('app-screen').find('#code-details').should('have.text', appDetails[expectedKey]);
}
Assuming that you have the expectedKey inside the cy.readFile(), you can do like this:
Create a custom command at cypress/support/commands.js:
Cypress.Commands.add('codeDetailsText', (expectedKey, appDetails) => {
expectedKeyCode = expectedKey.toLowerCase() + 'Code'
cy.get('app-screen')
.find('#code-details')
.should('have.text', appDetails[expectedKeyCode])
})
In your test just write:
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
//Assuming expectedKey value is available here
cy.codeDetailsText(expectedKey, appDetails)
})
I have a query:
topics = await topicRepository.createQueryBuilder('topic')
.leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')
.where('topic.categoryId = :id', {
id: categoryId,
})
.andWhere('topic.title like :search', { search: `%${searchKey}%`})
// It should take the first where
.orWhere('user.pseudo like :search', { search: `%${searchKey}%` })
.addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')
.take(limit)
.skip(skip)
.getMany();
Generated SQL query is:
SELECT DISTINCT distinctAlias.topic_id as \"ids_topic_id\", distinctAlias.topic_created_at FROM (SELECT topic.id AS topic_id, topic.title AS topic_title, topic.content AS topic_content, topic.created_at AS topic_created_at, topic.views AS topic_views, topic.repliesCount AS topic_repliesCount, topic.categoryId AS topic_categoryId, topic.userId AS topic_userId, topic.surveyId AS topic_surveyId, user.id AS user_id, user.email AS user_email, user.pseudo AS user_pseudo, user.password AS user_password, user.rank AS user_rank, user.avatar AS user_avatar, user.createdAt AS user_createdAt, user.lastActivity AS user_lastActivity, user.signature AS user_signature, user.post_count AS user_post_count, user.updatedAt AS user_updatedAt FROM topic topic LEFT JOIN user user ON user.id=topic.userId AND (topic.userId = user.id) WHERE topic.categoryId = '5' AND topic.title like '%admin%' OR topic.user.pseudo like '%admin%') distinctAlias ORDER BY distinctAlias.topic_created_at DESC, topic_id ASC LIMIT 20
The problem is here:
WHERE topic.categoryId = '5' AND topic.title like '%admin%' OR topic.user.pseudo like '%admin%')
I expected :
WHERE (topic.categoryId = '5' AND topic.title like '%admin%') OR (topic.categoryId = '5' AND topic.user.pseudo like '%admin%')
I want the .orWhere being OR from .andWhere instead .where
I don't find any documentation / issue about this use case.
The precedence of query conditions can be controlled by using the Brackets class:
topics = await topicRepository.createQueryBuilder('topic')
.leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')
.where('topic.categoryId = :id', {
id: categoryId,
})
.andWhere(new Brackets(qb => {
qb.where('topic.title like :search', { search: `%${searchKey}%`})
.orWhere('user.pseudo like :search', { search: `%${searchKey}%` });
}))
.addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')
.take(limit)
.skip(skip)
.getMany();
(edit: added period to correct syntax)
I want to create index with some condition,like with querycontainer to add conditional filters.
PropertiesDescriptor<object> ps = new PropertiesDescriptor<object>();
if (condition)
{
ps.Text(s => s.Name(name[1]));
}
if(condition)
{
ps.Number(s => s.Name(name[1]));
}
if (!_con.client.Indices.Exists(indexname).Exists)
{
var createIndexResponse = _con.client.Indices.Create(indexname, index => index.Settings(s => s.NumberOfShards(1).NumberOfReplicas(0))
.Map(m=>m.Properties(ps)));
}
But i receive following error, can you guide me how to acheive this.
cannot convert from 'Nest.PropertiesDescriptor<object>' to 'System.Func<Nest.PropertiesDescriptor<object>, Nest.IPromise<Nest.IProperties>>'
You are almost there, just change Properties part to m.Properties(p => ps).
_con.client.Indices.Create(indexname,
index => index.Settings(s => s.NumberOfShards(1).NumberOfReplicas(0)).Map(m=>m.Properties(p => ps)));
Hope that helps.
I can't figure out how to test my custom analyzer/view the analyzed data.
Normally I would add my custom analyzer to the "index settings" when creating the index. The problem I'm having in this case is that I'm not using an index or at least I think that I'm not and I don't know how to add my custom analyzer to the Elasticsearch client?
This is the method which I'm currently using for testing the "analysis" part:
public async Task AnalizeField(string analyzer, string textToAnalyze)
{
var elasticClient = ElasticsearchHelper.DatabaseConnection();
var analyzeResponse = await elasticClient.AnalyzeAsync(a => a
.Analyzer(analyzer)
.Text(textToAnalyze)
);
var result = "";
if (analyzeResponse != null && analyzeResponse.Tokens.Count > 0)
{
foreach (var token in analyzeResponse.Tokens)
{
result += token.Token + " ";
}
}
Console.WriteLine("Analyzing text \"" + textToAnalyze + "\" using the \"" + analyzer + "\" analyzer: " + result);
}
Found it: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/testing-analyzers.html#_testing_a_custom_analyzer_in_an_index
Testing a custom analyzer in an index
In this example, we’ll add a custom analyzer to an existing index. First, we need to close the index
client.CloseIndex("analysis-index");
Now, we can update the settings to add the analyzer
client.UpdateIndexSettings("analysis-index", i => i
.IndexSettings(s => s
.Analysis(a => a
.CharFilters(cf => cf
.Mapping("my_char_filter", m => m
.Mappings("F# => FSharp")
)
)
.TokenFilters(tf => tf
.Synonym("my_synonym", sf => sf
.Synonyms("superior, great")
)
)
.Analyzers(an => an
.Custom("my_analyzer", ca => ca
.Tokenizer("standard")
.CharFilters("my_char_filter")
.Filters("lowercase", "stop", "my_synonym")
)
)
)
)
);
And open the index again. Here, we also wait up to five seconds for the status of the index to become green
client.OpenIndex("analysis-index");
client.ClusterHealth(h => h
.WaitForStatus(WaitForStatus.Green)
.Index("analysis-index")
.Timeout(TimeSpan.FromSeconds(5))
);
With the index open and ready, let’s test the analyzer
var analyzeResponse = client.Analyze(a => a
.Index("analysis-index")
.Analyzer("my_analyzer")
.Text("F# is THE SUPERIOR language :)")
);
you should try to install Cerebro.
https://github.com/lmenezes/cerebro
After you install it you have in the menu Analysis. Then you can easily see "analyze by field type" or "analyze by analyzer".
This should help
I have the following query
var searchResult = _Db.Search<PackageRecord>( s => s
.Index( user.Tenant.Id.ToString () )
.Type( "Package" )
.From( request.Page )
.Size( _DefaultPageSize )
.Query( q => q.Nested( n => n
.Path ( f => f.List_BorrowerSet[0] )
.Query( qm => qm.QueryString( qs => qs
.OnFields (
f => f.List_BorrowerSet.First().PrimaryBorrower.ContactDetails.Name_Fist,
f => f.List_BorrowerSet.First().PrimaryBorrower.ContactDetails.Name_Last
)
.Query ( request.BorrowerName ) )
&& qm
.Term (
f => f.List_BorrowerSet.First().PrintPosition , 0 )
) ) )
.Fields(
f => f.Id,
f=> f.List_BorrowerSet[0].PrimaryBorrower.ContactDetails.Name_Fist,
f=> f.List_BorrowerSet[0].PrimaryBorrower.ContactDetails.Name_Last
)
);
How can I get the result with just the limited fields? I see a document and hits but their object has List_BorrowerSet as null.
When you specify .Fields() elasticsearch will always return the field selections as key value pairs i.e:
"fields" {
"list_borrowerSet.primaryBorrow.contactDetails.name_Last" : ["Martijn"],
"list_borrowerSet.primaryBorrow.contactDetails.name_Fist" : ["Laarman"]
}
JSON.NET and thus NEST does not quite know how to deserialize these back into a PackageRecord
if you would only select f.List_BorrowerSet then NEST/JSON.NET can deserialize it properly into PackageRecord
You are better off specifying your search as followed:
var searchResult = _Db.Search<PackageRecord,CustomPackageRecordSearchHit>( s => s
....
Now nest will use PackageRecord type to build the search but CustomPacakgeRecordSearchHit to deserialize the hits:
public class CustomPackageRecordSearchHit
{
[JsonProperty("list_borrowerSet.primaryBorrow.contactDetails.name_Fist")]
public IEnumerable<string> BorrowersFirstNames { get; set; }
}
Depending on the size of your json this may or may not be a premature optimalization so make sure returning f.List_BorrowerSet as a field incurs a signaficant overhead.