Grails searcheble don't use field during fulltext search - grails

Domain (just simple example):
class House {
String address
String region
Long price
static searchable = { only = ['address', 'price', 'region'] }
}
I want to search by address with price selector
Search query is:
"${address} AND price: [100 TO 1000]"
But if address='500' in search result will be Houses with price 500. I need to find house for address only by House.address + House.region

If I understood, you want to use the value of ${address} to query only on the address and region attributes.
In that case, based on the "complex" query string example at http://grails.org/Searchable+Plugin+-+Searching+-+String+Queries, your query string could be:
"+(address:${address} OR region:${address}) price:[100 TO 1000]"
Matches must have a ${address} value for address or a ${address} value for region, and have a value from 100 to 1000 for price.
Note: your input variable has the same name of an entity attribute, "address", wich can cause some confusion when trying to understand query strings using them both. Though not needed, you might want to change that, for easier readable query strings.

Related

Searching for specific characters in user input

Within my house table I have a postcode for each house.
I also have an index view for my housing table that contains a table which contains headings such as 'Name', 'Address', 'State'. I was looking to integrate a text_field_tag that would allow user's to input the 9 digits of a postcode in order to filter the table to only show the house with that postcode. However, I also want the user to be able to input the first 4 digits of their postcode e.g. '7644' and it would display all houses that begin with '7644' e.g. two records one with the postcode of the '76444-5645' and '76443-123'. Ideally I would apply logic through my '#search' variable within my houses controller. However I am up to any ideas or tips.
In order to instantiate the house model I would use #house = House.all
I'll be honest I don't know where to begin with this. I have arel_sql in my system so I assume that would be used to query for the search.
It depends on how your models/controllers are defined but you're probably looking for the SQL operator LIKE + '%', which allows you to search for a pattern in a given column. Example:
LIKE Operator
Description
WHERE CustomerName LIKE 'a%'
Finds any values that start with "a"
Assuming you're using ActiveRecord and your model is House, it wouldn't event need to instantiate all houses. Your code would look something like this:
postcode = '7644'
#houses = House.where('postcode LIKE ?', "#{postcode}%") # this returns where the postcode starts with '7644'
another similar SO answer for reference

How to search product data by id and name in one query

I have a index named product in elastic-search with field id, name etc..
I want to search products by id or name but my id field is integer and name is a text, I tried following but getting error while searching by name.
error type":"number_format_exception","reason":"For input string:
\"test\""
def self.search_by_name_or_id(query)
__elasticsearch__.search({
query: {
bool: {
must:{
multi_match: {
query: query,
fields: ["id", "name"]
}
}
}
}
})
end
Problem
Exception is clear, that you are trying to search test which is a String in the integer field and elasticsearch is not able to convert test in integer, instead of test if you had search for 10 or 100, then elasticsearch would convert it into integer and would not throw the exception.
Solution
You are trying to mix 2 things here, I am not sure about your design but if your id field can contain pure numbers i.e. integers, then it's not possible to achieve in a single query the way you are doing.
If you can convert your id field to String, then multi_match query would work perfectly fine, otherwise, you need to first check in your application, that search term can be converted to number or not, i.e. 10 or 100 would work fine but test10 or test100 would not and anyway there is no point of searching these terms in id field as it won't be present as its defined as integer in ES and ES would reject documents containing these terms during indexing time only. So based on your application code check you can construct the ES query which may or may not include the id field in multi-match.

Searching for matching records in a field saved as a hash in PostgreSQL?

I have an active record SearchSuggestion that has a title:text field for storing values for different languages in a single hash that looks like so:
#<SearchSuggestion :id 1, link: "/search/shoes", title: {"en"=>"Women's shoes", "ko"=>"여성 신발", "ru"=>"Женская Обувь", "fr"=>"Chaussures De Femme"}>
and I'm fetching records that match the given input in the following way: all of the given words contained in all records' title fields, starting only from the start of each word the following way:
query = params[:q].split(" ").map{|s| s.prepend('(?:.*\m')}.map{|s| s.concat(')')}.join('')
SearchSuggestion.where("title ~* ?", query).limit(10).pluck(:title)
The problem is that this gives me matches from the whole field, and I want just the ones for the current selected language. So if I have languages that are using the same alphabet - I get unrelated results e.g - if I start typing "cha" this will return "Women's shoes" by finding the French suggestion as a match. Also if I type "en" - I get all of the existing records as a result, because they match the key for "en" language.
Is there any way I can specify the hash's key that I only want to search within?

Realm not query string field with whitespace

I have such function in my data source:
func getAllFood(by type: String) -> [UserFoodInformation] {
var findedFood = [UserFoodInformation]()
findedFood.append(contentsOf: baseUserFoodDataSource.getAllFood(by: type))
let predicate = NSPredicate(format: "foodType == %#", type)
let resultOfSearching = dataBase.objects(AddedUserFood.self).filter(predicate).sorted(byKeyPath: "name")
for searchedFood in resultOfSearching {
findedFood.append(searchedFood)
}
return findedFood
}
When I try to query with string that consist whitespace, I have no result, but if I query with simple one-word parameter, everything goes fine. Why is that? Can I have a string field in Realm that consists multiple words?
The predicate you're using is looking for objects whose foodType property is equal to the type string that is passed in. Only those objects whose property is exactly equal to that string will match. If you want to perform some other form of matching you'll need to use something other than the equality operator. BEGINSWITH, CONTAINS, ENDSWITH and LIKE are the comparison operators that Realm supports on string fields.
Can I have a string field in Realm that consists multiple words?
String fields can contain any string values. The supported comparison operators don't have the concept of a "word", though, so if you want to do filtering using that concept you'll likely need to do further work on your part. Depending on your use case, I can see a couple of ways to go about it:
Use CONTAINS to find any objects whose foodType properties contains the given type string.
Parse the string into structured data that you store in your model. For instance, it may make sense to store a List<FoodType> rather than a String for the foodType property.
There are likely other options, but they depend on details of what it is you're trying to achieve that you've not shared.

Searching for Parse objects where an object's array property contains a specified string

I have a PFObject subclass which stores an array of strings as one of its properties. I would like to query for all objects of this class where one or more of these strings start with a provided substring.
An example might help:
I have a Person class which stores a firstName and lastName. I would like to submit a PFQuery that searches for Person objects that match on name. Specifically, a person should be be considered a match if if any ‘component’ of either the first or last name start with the provided search term.
For example, the name "Mary Beth Smith-Jones" should be considered a match for beth and bet, but not eth.
To assist with this, I have a beforeSave trigger for the Person class that breaks down the person's first and last names into separate components (and also lowercases them). This means that my "Mary Beth Smith-Jones" record looks like this:
firstName: “Mary Beth”
lastName: “Smith-Jones”
searchTerms: [“mary”, “beth”, “smith”, “jones”]
The closest I can get is to use whereKey:EqualTo which will actually return matches when run against an array:
let query = Person.query()
query?.whereKey(“searchTerms”, equalTo: “beth”)
query?.findObjectsInBackgroundWithBlock({ (places, error) -> Void in
//Mary Beth is retuned successfully
})
However, this only matches on full string equality; query?.whereKey(“searchTerms”, equalTo: “bet”) does not return the record in question.
I suppose I could explode the names and store all possible sequential components as search terms (b,e,t,h,be,et,th,bet,etc,beth, etc) but that is far from scalable.
Any suggestions for pulling these records from Parse? I am open to changing my approach if necessary.
Have you tried whereKey:hasPrefix: for this? I am not sure if this can be used on array values.
https://parse.com/docs/ios/guide#queries-queries-on-string-values

Resources