i am not able to create a collection in ravendb, if i do not have any document in it - database

I have created a document in ravendb. Using session.advanced.getmetadata(see in code) , i gave a name to Raven-Entity-Name in metadata, after that i deleted that document in same function.Then i saw collection is also removed.If i delete the document manually from raven studio then the collection remains in the database.How a collection persist even if there is no document from code part? thanks in advance !!
My c# code is :
public CreateCollectionResult CreateCollection(string databaseName, string collectionName)
{
CreateCollectionResult createCollectionResult = new CreateCollectionResult();
Collection collection1234 = new Collection();
try
{
using (var session = documentStore.OpenSession(databaseName))
{
Guid guid = new Guid("12345678-1111-1111-2222-000000000000");
session.Store(collection1234, guid, "april-Days/10");
session.Advanced.GetMetadataFor<Collection>(collection1234)[Constants.RavenEntityName] = collectionName;
//session.Delete<Collection>(collection1234);
session.SaveChanges();
createCollectionResult.IsOperationSuccessfull = true;
}
}
//exception if database not found
catch (InvalidOperationException ex)
{
createCollectionResult.IsOperationSuccessfull = false;
createCollectionResult.Error = ex;
}
return createCollectionResult;
}

In RavenDB, collections are virtual, they are only there as long as you have at least one doc in that document.

Related

Java solrclient group query

I am building a chat like app and I am storing the chat conversation in Solr 6.5.1.
I have created a message collection and every document corresponds to a single message exchanged between two users. A document has a fromId and a toId like below.
I want to group the messages by toId and show a count of how many messages per conversation with a user. I am able to test it using admin UI like so.
But from my Java code using SolrJ I am unable to get the same result. Below is my code snippet
SolrQuery query = new SolrQuery();
query.set("wt", "json");
query.setQuery("fromId:1234");
query.set("group",true);
query.set("group.field", "toId");
try {
GroupResponse gRes = client.query(query).getGroupResponse();
List<GroupCommand> groupCommands = gRes.getValues();
List<GroupResult> grs = new ArrayList<>();
for(GroupCommand gc : groupCommands){
GroupResult gr = new GroupResult();
gr.setCount(gc.getMatches());
gr.setGroupText(gc.getName());
grs.add(gr);
}
return grs;
} catch (SolrServerException | IOException e) {
e.printStackTrace();
return Collections.EMPTY_LIST;
}
But this is not giving me both the groups , instead I am only getting one group with matched count as 6 .
Please help
Answering my own question. Below is the change required to my code in order to get to the groups.
QueryResponse gRes = client.query(query);
GroupResponse grpR = gRes.getGroupResponse();
List<GroupCommand> groupCommands = gRes.getGroupResponse().getValues();
List<GroupResult> grs = new ArrayList<>();
for(GroupCommand gc : groupCommands){
List<Group> groups = gc.getValues();
for(Group group : groups){
GroupResult gr = new GroupResult();
gr.setGroupText(group.getGroupValue());
gr.setCount(group.getResult().getNumFound());
grs.add(gr);
}
}

Entity Framework : Create a model from Dictionary<TKey,TValue> to be mapped to a database table

Earlier I had a table named ApplicationConfiguration which simply had [Key],[Value] columns to store some config data. This was queried straight away using SQL queries.
Now I intend to make use of Entity Framework (EF) Code First approach to query this table. The specialty of this table is that the table will have only a fixed number of rows in its lifetime. Only the Value column can be updated.
So as per the code first approach, we have to first write our POCO classes with its properties that will be mapped to columns in the underlying table. However, I wish to have a Dictionary<> structure to represent these configuration KV pairs. My concern is, will EF be able to fire update queries against any updation to the the value of a particular pair.
Also since I am using Code First approach, I would want some seed data(i.e the fixed number of rows and its initial content) to the added after the table itself is created on the fly when the application is first executed.
If Dictionary<> cannot be used, please suggest some alternative. Thanks in advance.
Coded this way:
public class ApplicationConfiguration
{
public int Id { get; set; }
public string Key { get; set; }
public int Value { get; set; } // should be string, but I'm lazy
}
class Context : DbContext
{
internal class ContextInitializer : DropCreateDatabaseIfModelChanges<Context>
{
protected override void Seed(Context context)
{
var defaults = new List<ApplicationConfiguration>
{
new ApplicationConfiguration {Key = "Top", Value = 5},
new ApplicationConfiguration {Key = "Bottom", Value = 7},
new ApplicationConfiguration {Key = "Left", Value = 1},
new ApplicationConfiguration {Key = "Right", Value = 3}
};
// foreach (var c in defaults)
// context.ConfigurationMap.Add(c.Key, c); // by design, no IReadOnlyDictionary.Add
foreach (var c in defaults)
context.ApplicationConfigurations.Add(c);
base.Seed(context);
}
}
public Context()
{
Database.SetInitializer(new ContextInitializer());
}
private IDbSet<ApplicationConfiguration> ApplicationConfigurations
{
get { return Set<ApplicationConfiguration>(); }
}
public IReadOnlyDictionary<string, ApplicationConfiguration> ConfigurationMap
{
get { return ApplicationConfigurations.ToDictionary(kvp => kvp.Key, kvp => kvp); }
}
}
Used this way:
using (var context = new Context())
{
ReadConfigurationOnly(context.ConfigurationMap);
}
using (var context = new Context())
{
ModifyConfiguration(context.ConfigurationMap);
context.SaveChanges();
}
static void ReadConfigurationOnly(IReadOnlyDictionary<string, ApplicationConfiguration> configuration)
{
foreach (var k in configuration.Keys)
Console.WriteLine("{0} = {1}", k, configuration[k].Value);
}
static void ModifyConfiguration(IReadOnlyDictionary<string, ApplicationConfiguration> configuration)
{
foreach (var k in configuration.Keys)
configuration[k].Value++; // this is why I was lazy, using an int for a string
}
So, I wrote it up this way — using an int Value property rather than a string — just so I could run the "Used this way" code over and over, and see the database update each time, without having to come up with some other way to change Value in an interesting way.
It's not quite as nifty here to use a IReadOnlyDictionary<string, ApplicatonConfiguration> instead of a IReadOnlyDictionary<string, string>, the way we'd really like, but that's more than made up for by the fact that we can easily modify our collection values without resorting to a clumsier Set method taking a dictionary as input. The drawback, of course, is that we have to settle for configuration[key].Value = "new value" rather than configuration[key] = "new value", but — as I say — I think it's worth it.
EDIT
Dang! I wrote this code up specifically to answer this question, but I think I like it so much, I'm going to add it to my bag of tricks ... this would fit in really well when my company goes from local databases to Azure instances in the cloud, and the current app.config has to go into the database.
Now all I need is a ContextInitializer taking a System.Configuration.ConfigurationManager as a ctor parameter in order to seed a new database from an existing app.config ...
I don't think you can map a table directly to a Dictionary; you will probably have to write your own wrapper to fill a dictionary from the table and update it back to the DB. Entities are each a row of a given table... Something like this (untested):
public Dictionary<string, string> GetDictionary()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
using (var db = new Context())
{
var configs = db.ApplicationConfiguration.Select();
foreach (var entry in configs)
{
dic.Add(config.Key, config.Value);
}
}
return dic;
}
public void SaveConfig(Dictionary<string, string> dic)
{
using (var db = new Context())
{
foreach (KeyValuePair kvp in dic)
{
if (!db.ApplicationConfiguration.First(a => a.Key == kvp.Key).Value == kvp.Value)
{
var ac = new ApplicationConfiguration();
ac.Key = kvp.Key;
ac.Value = kvp.Value;
db.Entry(ac).State = EntityState.Modified;
}
}
db.SaveChanges();
}
}
For your second question, you want to use the Seed() method to add initial values to the database. See here for an example implementation.

Why does this code - adding wordnet synonyms to index - fail?

I am writing this code as part of my CustomAnalyzer:
public class CustomAnalyzer extends Analyzer {
SynonymMap mySynonymMap = null;
CustomAnalyzer() throws IOException {
SynonymMap.Builder builder = new SynonymMap.Builder(true);
FileReader fr = new FileReader("/home/watsonuser/Downloads/wordnetSynonyms.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
String[] synset = line.split(",");
for(String syn: synset)
builder.add(new CharsRef(synset[0]), new CharsRef(syn), true);
}
br.close();
fr.close();
try {
mySynonymMap = builder.build();
} catch (IOException e) {
System.out.println("Unable to build synonymMap");
e.printStackTrace();
}
}
public TokenStream tokenStream(String fieldName, Reader reader) {
TokenStream result = new PorterStemFilter(new SynonymFilter(
(new StopFilter(true,new LowerCaseFilter
(new StandardFilter(new StandardTokenizer
(Version.LUCENE_36,reader)
)
),StopAnalyzer.ENGLISH_STOP_WORDS_SET)), mySynonymMap, true)
);
}
}
Now, if I use the same CustomAnalyzer as part of my querying, then if I enter the query as
myFieldName: manager
it expands the query with synonyms for manager.
But, I want the synonyms to be part of only my index and I don't want my query to be expanded with synonyms.
So, when I removed the SynonymFilter from my CustomAnalyzer only when querying the index, the query remains as
myFieldName: manager
but, it fails to retrieve documents that have the synonyms of manager.
How do we solve this problem?
If you do not have your synonym builder during Query processing then the only term it will match is what you mapped to during indexing. And you are not showing that part here.
The best way to troubleshoot this is to look at Admin/Core/Analysis screen (in Solr 4+) and put your text in. It will show what happens with the text after each stage in indexing and queries is run.
You don't even need to run reindexer. You can just define a bunch of different types you are trying to figure out and then run the analysis of the sample sentences directly against those types.

How to know the order of update with Domain context SubmitChanges?

Suppose I have 3 entities generated from EF, say tab1, tab2 and tab3. In SL app, I call SubmitChanges to save data to DB, all changes will be process by WCF and EF automatically.
Question is: how can I know the order of Update operation in Database?
I need to know this because I have triggers on those tables and need to know the order of the updating.
One thing you can do is to override the PeristChangeSet() in your DomainService and manually control the order of saves. Just do nothing in your regular update/insert statements. Here's some pseudocode for a saving a document exmmple to explain my answer:
[Insert]
public void InsertDocument(MyDocument objDocument) { }
[Update]
public void UpdateDocument(MyDocument objDocument) { }
protected override bool PersistChangeSet()
{
try {
// have to save document first to get its id....
MyDocument objDocumentBeingSaved = null;
foreach (ChangeSetEntry CSE in ChangeSet.ChangeSetEntries.Where(i => i.Entity is MyDocument)) {
var changedEntity = (MyDocument)CSE.Entity;
objDocumentBeingSaved = documentRepository.SaveDocument(changedEntity);
break; // only one doc
}
if (objDocumentBeingSaved == null)
throw new NullReferenceException("CreateDocumentDomainService.PersistChangeSet(): Error saving document information. Document is null in entity set.");
// save document assignments after saving document object
foreach (ChangeSetEntry CSE in ChangeSet.ChangeSetEntries.Where(i => i.Entity is DocumentAssignment)) {
var changedEntity = (DocumentAssignment)CSE.Entity;
changedEntity.DocumentId = objDocumentBeingSaved.Id;
changedEntity.Id = documentRepository.SaveDocumentAssignment(objDocumentBeingSaved, changedEntity);
}
// save line items after saving document assignments
foreach (ChangeSetEntry CSE in ChangeSet.ChangeSetEntries.Where(i => i.Entity is LineItem)) {
var changedEntity = (LineItem)CSE.Entity;
changedEntity.DocumentId = objDocumentBeingSaved.Id;
changedEntity.Id = documentRepository.SaveLineItem(objDocumentBeingSaved, changedEntity);
}
documentRepository.GenerateDocumentNumber(objDocumentBeingSaved.Id);
}
catch {
// ....
throw;
}
return false;
}

Is my LDAP syntax wrong in search filter

This is my first attempt in trying to query our LDAP server for AD info. When I am trying to query the LDAP server here is what I'm trying to retrieve:
I am trying to retrieve all active employees with a countlimit of 500 records whose displayname starts with "sav", has an email address and has a userAccountControl attribute of 512. The problem I'm encountering is that I'm only getting back 8 records total. I should literally be getting back at least 10 records.
I did a separate search on the 2 records that were NOT retrieved in my search and each had an email address and a userAccountControl value of 512. So I'm not sure why those 2 records were missing.
I'm sure I've done something wrong in my syntax but I cannot find what it is. Any HELP/DIRECTION would be appreciated. Thank you.
After googling I've defined the SEARCH FILTER as:
String searchFilter = "(&(objectClass=user)(displayname="+displayname+"*"+")(mail=*)(userAccountControl=512))";
Please see my complete method below:
public List<String> getAutocompleteEmpRecordsList(String displayname, LdapContext ctx) {
List<String> activeEmpAttributes = new ArrayList<String>();
Attributes attrs = null;
int count = 0;
int empEmailAddrLen = 0;
try {
SearchControls constraints = new SearchControls();
constraints.setCountLimit(500);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"displayname", "mail", "userAccountControl"};
constraints.setReturningAttributes(attrIDs);
String searchFilter = "(&(objectClass=user)(displayname="+displayname+"*"+")(mail=*)(userAccountControl=512))";
NamingEnumeration answer = ctx.search("OU=Standard,OU=Users,DC=xxx,DC=org", searchFilter, constraints);
if (answer != null) {
while (answer.hasMore()) {
attrs = ((SearchResult) answer.next()).getAttributes();
if (attrs.get("displayname") != null) {
int empNameLen = attrs.get("displayname").toString().length();
activeEmpAttributes.add(attrs.get("displayname").toString().substring(13, empNameLen));
}
count++;
ctx.close();
}
}
else {
throw new Exception("Invalid User");
}
System.out.println("activeEmpAttributes: " + activeEmpAttributes);
System.out.println("count: " + activeEmpAttributes.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return activeEmpAttributes;
}
You may be confusing displayname attribute and cn attribute.
On Windows server you've got a command line tool called LDIDIFDE.EXE which can allow you to test your filter.
ldifde -f datas.ldf -d "OU=Standard,OU=THR Users,DC=txhealth,DC=org" -r "(&(objectClass=user)(displayname=sav*)(mail=*)(userAccountControl=512))"
ldifde -f datas.ldf -d "OU=Standard,OU=THR Users,DC=txhealth,DC=org" -r "(&(objectClass=user)(cn=sav*)(mail=*)(userAccountControl=512))"
In the User and computer MMC you can also test your filter.
Start User and computer Active-Directory :
Right buton on registered request :
Choose personalize search, you've got an helper tab for common attributes :
You can choose personalized tab for technical attributes
You can test en copy the resulting LDAP filter (you don't need the double (& one is enough):
Can you post your userAccountControl, displayName, and mail values for the two excluded users?
FWIW the medial search on displayName would run alot faster if you add a tuple index to it.
I downloaded a free AD tool to view all in AD that I needed and it showed me that the data was not the problem but I was just not hitting all the OU's that I needed because there is NOT just 1 OU where all our users are stored.
Consequently, after googling some more I found a page on the Oracle site regarding LDAP and I changed my LDAPContext to DirContext for my connection to do searches within the directory as well as using this context's REFERRAL and set the value to "follow" to avoid the PartialSearchException.
I thought I'd post my findings just in case some other newbie ran into the same issue.
If you see a downside to the changes I made please let me know. Regards.
Here is my corrected code:
public List<String> getAutocompleteEmpRecordsList(String displayname, DirContext ctx) {
List<String> activeEmpAttributes = new ArrayList<String>();
Attributes attrs = null;
int count = 0;
int empEmailAddrLen = 0;
try {
SearchControls constraints = new SearchControls();
constraints.setCountLimit(500);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"displayname", "mail", "userAccountControl"};
constraints.setReturningAttributes(attrIDs);
String searchFilter = "(&(objectClass=user)(displayname="+displayname.trim()+"*"+")(mail=*)(userAccountControl=512))";
NamingEnumeration answer = ctx.search("DC=xxx,DC=org", searchFilter, constraints);
if (answer != null) {
while (answer.hasMore()) {
attrs = ((SearchResult) answer.next()).getAttributes();
if (attrs.get("displayname") != null) {
int empNameLen = attrs.get("displayname").toString().length();
activeEmpAttributes.add(attrs.get("displayname").toString().substring(13, empNameLen));
}
count++;
ctx.close();
}
}
else {
throw new Exception("Invalid User");
}
System.out.println("activeEmpAttributes: " + activeEmpAttributes);
System.out.println("count: " + activeEmpAttributes.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return activeEmpAttributes;
}
Thanks anyway.

Resources