How to query mongoengine by using contains in list? - mongodb

If I have a collection with a list field similar to the below.
class Post(Document):
tags = ListField(StringField())
Let's say I have a post with the tags: interesting, funny.
And if I want to search for posts with tags fulfill any of the search terms, how should I do?
Say if I put in the search terms "interesting" and "fantastic", the above post should be there in the result set.
I tried to read through documentation but seems like there is no such operator. "all" and "in" are similar but can't perform what I want.

This is actually just a simple query eg:
class Post(Document):
tags = ListField(StringField())
>>> Post.drop_collection()
>>> Post(tags=["hello", "world"]).save()
>>> Post(tags=["cat", "dog"]).save()
>>> Post.objects(tags__in=['hello', 'cat']).count()
... 2
What this equates to is find any documents that have hello in tags. In would go a search where any of the items in the 'in' array match and all is where all items match - or in other words an exact match.

Related

How to check if list of string contains (substring) value in EpiFind?

I have indexed an object which has a list of strings like ["ZZA-KL-2A", "ZZA-KL-ZZB"]. I want to search and get all items which starts with a certain 3 letter code. So I want to check each item in the list and check something like 'StartsWith'.
I can see from documentation that we have something like Match, MatchContained but nothing for start with for the list of string items.
Please note that this question is not related to ordinary string comparison in C# or LINQ before flagging the question.
Just use a filter
var searchQuery = client.Search<MyContent>()
.Filter(x => x.OrderNumber.StartsWith("Find"));
https://world.episerver.com/documentation/developer-guides/search-navigation/NET-Client-API/searching/Filtering/
You may use Prefix or PrefixCaseInsensitive:
Matching by beginning of a string (startsWith)
The Prefix method lets you match by the beginning of a string. The
following search matches blog posts titled Find and Find rocks! but
not find, Finding or Hello Find.
var searchQuery = client.Search<BlogPost>().Filter(x =>
x.Title.Prefix("Find"));
Use the PrefixCaseInsensitive method to match by the beginning of a
string in a case-insensitive way. The following search matches blog
posts titled Find, Find rocks! and Find but not Finding or Hello Find.
var searchQuery = client.Search<BlogPost>().Filter(x =>
x.Title.PrefixCaseInsensitive("Find"));
Source: https://docs.developers.optimizely.com/digital-experience-platform/v1.1.0-search-and-navigation/docs/strings#matching-by-beginning-of-a-string-startswith

How can you filter search by matching String to a field in Algolia?

I'm trying to create filters for a search on an Android app where a specific field in Algolia must exactly match the given String in order to come up as a hit. For example if Algolia has a field like "foo" and I only want to return hits where "foo" is equal to "bar", then I would expect that I would have to use a line of code like this:
query.setFilters("foo: \"bar\"");
Any guesses as to why this isn't working like I see in the examples or how to do so?
Ah, I thought that attributesForFaceting was done by setting what was searchable or not. It was on a different page within the dashboard than I was previously using. Thanks #pixelastic.

how to find partial search in Mongodb?

How to find partial search?
Now Im trying to find
db.content.find({$text: {$search: "Customer london"}})
It finds all records matching customer, and all records matching london.
If I am searching for a part of a word for example lond or custom
db.content.find({$text: {$search: "lond"}})
It returns an empty result. How can I modify the query to get the same result like when I am searching for london?
You can use regex to get around with it (https://docs.mongodb.com/manual/reference/operator/query/regex/). However, it will work for following :
if you have word Cooking, following queries may give you result
cooking(exact matching)
coo(part of the word)
cooked(The word containing the english root of the document word, where cook is the root word from which cooking or cooked are derived)
If you would like to go one step further and get a result document containing cooking when you type vooking (missplled V instead of C), go for elasticsearch.
Elasticsearch is easy to setup, has extremely powerful edge-ngram analyzer which converts each words into smaller weightage words. Hence when you misspell, you will still get a document based on score elasticsearch gives to that document.
You can read about it here : https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html
it will always return the empty array for partial words like when you are searching for lond to get this type of text london..
Because it take full words and search same as that they are ..
Not achive same results like :-
LO LON LOND LONDO LONDON
Here you may get help from ELASTIC-SEARCH . It is quite good for full text search when implement with mongoDB.
Refrence : ElasticSearch
Thanks
The find all is to an Array
clientDB.collection('details').find({}).toArray().then((docs) =>
I now used the str.StartWith in a for loop to pick out my record.
if (docs[i].name.startsWith('U', 0)) {
return console.log(docs[i].name);
} else {
console.log('Record not found!!!')
};
This may not be efficient, but it works for now

Mongoid, find object by searching by part of the Id?

I want to be able to search for my objects by searching for the last 4 characters of the id. How can I do that?
Book.where(_id: params[:q])
Where the param would be something like a3f4, and in this case the actual id for the object that I want to be found would be:
bc313c1f5053b66121a8a3f4
Notice the last for characters are what we searched for. How can I search for just "part" of my objects id? instead of having my user search manually by typing in the entire id?
I found in MongoDB's help docs, that I can provide a regex:
db.x.find({someId : {$regex : "123\\[456\\]"}}) // use "\\" to escape
Is there a way for me to search using the regular mongo ruby driver and not using Mongoid?
Usually, in Mongoid you can search with a regexp like you normally would with a string in your call to where() ie:
Book.where(:title => /^Alice/) # returns all books with titles starting with 'Alice'
However this doesn't work in your case, because the _id field is not stored as a string, but as an ObjectID. However, you could add (and index) a field on your models which could provide this functionality for you, which you can populate in an after_create callback.
<shameless_plug>
Alternatively, if you're just looking for a shorter solution to the default Mongoid IDs, I could suggest something like mongoid_token which makes it pretty easy to add shorter tokens/ids to your Mongoid documents.
</shameless_plug>

Why is this Lucene query a "contains" instead of a "startsWith"?

string q = "m";
Query query = new QueryParser("company", new StandardAnalyzer()).Parse(q+"*");
will result in query being a prefixQuery :company:a*
Still I will get results like "Fleet Africa" where it is rather obvious that the A is not at the start and thus gives me undesired results.
Query query = new TermQuery(new Term("company", q+"*"));
will result in query being a termQuery :company:a* and not returning any results. Probably because it interprets the query as an exact match and none of my values are the "a*" literal.
Query query = new WildcardQuery(new Term("company", q+"*"));
will return the same results as the prefixquery;
What am I doing wrong?
StandardAnalyzer will tokenize "Fleet Africa" into "fleet" and "africa". Your a* search will match the later term.
If you want to consider "Fleet Africa" as one single term, use an analyzer that does not break up your string on whitespaces. KeywordAnalyzer is an example, but you may still want to lowercase your data so queries are case insensitive.
The short answer: all your queries do not constrain the search to the start of the field.
You need an EdgeNGramTokenFilter or something like it.
See this question for an implementation of autocomplete in Lucene.
Another solution could be to use StringField to store the data for ex: "Fleet Africa"
Then use a WildCardQuery.. Now f* or F* would give results but A* or a* won't.
StringField is indexed but not tokenized.