Hibernate Search DSL and Lucene query on Multiple Fields - lucene

I'm not really sure how involved this might be, but could someone help me with below problem.
I'm trying to implement search functionality in my project based on employee firt and last name. I have used Spring Data REST and Hibernate Search for this purpose.
#Transactional
public search(String searchText) {
FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search
.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Employee.class).get();
org.apache.lucene.search.Query luceneQuery = qb.keyword().wildcard()
.onFields("firstName", "middleName", "lastName").matching(searchText + "*").createQuery();
javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Employee.class);
List result = jpaQuery.getResultList();
List<EmployeeSearchDTO> listOfDTO = new ArrayList<>();
EmployeeSearchDTO employeeDTO;
Iterator<Employee> itr = result.iterator();
while (itr.hasNext()) {
Employee employee = itr.next();
employeeDTO = new EmployeeSearchDTO(employee);
listOfDTO.add(employeeDTO);
}
}
When I search "john doe" i expect the results should match the below two
FirstName : John LastName : Doe
FirstName : johnathan LastName : Doe
But that is not the case and I'm able to search only based on FirstName["john"] or LastName["doe"] but not with both.
How do I solve this, any pointers would be greatly appreciated. Thanksin advance.

You really want to create two queries, one against the first name and one against the last name and then combine them via the SHOULD operator. Something like
Query combinedQuery = querybuilder
.bool()
.should( firstNameQuery )
.should( lastNameQuery )
.createQuery();
This means you are looking for results where either of the queries match.

Related

Transforming Raw Sql to Laravel equolent

I have written this SQL code
SELECT drugs.*, COUNT(*) as 'views' from drugs INNER JOIN drug_seen on drugs.id = drug_seen.drug_id GROUP BY drugs.id order by views ASC
And now I am trying to write in in the Laravel equolent but I am facing some troubles.
This is what I have tried
$drugs = Drug::select(DB::raw('drugs.*,count(*) as views'))
->join('drug_seen', 'drugs.id', 'drug_seen.drug.id')
->groupBy('drug.id')->orderByRaw('views');
I am having errors like column not found i think the code is not written properly
Drug class
class Drug extends Model
{
use HasFactory;
use SoftDeletes;
...
...
...
public function drugVisits()
{
return $this->hasMany(DrugSeen::class);
}
Hop this will solve your problem.
$drugs = Drug::with('drugVisits')->get();
$drugs->count(); //for total records in drugs table.
You have typo error in join instead on drug_id you use drug.id
Try this:
$drugs = Drug::select(DB::raw('drugs.*,count(*) as views'))
->join('drug_seen', 'drugs.id', 'drug_seen.drug_id')
->groupBy('drugs.id')->orderByRaw('views');
}
As soon as you use join() you're leaving Eloquent and entering Query\Builder, losing the benefits of Model configurations in the process. And with() eager-loads aren't the answer, if you're looking to filter the results by both tables. What you want is whereHas().
Also, as far as your grouping and count manipulation there, I think you're looking more for Collection handling than SQL groups.
$drugModel = app(Drugs::class);
$results = $drugModel->whereHas('drugVisits')->with('drugVisits')->get();
$organizedResults = $results
->groupBy($drugModel->getKey())
->sortyBy(function (Drugs $drugRecord) {
return $drugRecord->drugVisits->count();
});
If you want to have a 'views' property that carries the count in the root-level element, it would look like this:
$drugModel = app(Drugs::class);
$results = $drugModel->whereHas('drugVisits')->with('drugVisits')->get();
$organizedResults = $results
->groupBy($drugModel->getKey())
->map(function (Drugs $drugRecord) {
$drugRecord->views = $drugRecord->drugVisits->count();
return $drugRecord;
});
->sortyBy('views');

Lucene query in Liferay

I am looking for how to create a lucene query for the condition – className AND (“Apple-Orange” OR “Apple Banana” OR “Apple Shake”)
I tried
BooleanQuery specialityQuery = BooleanQueryFactoryUtil.create(searchContext);
specialityQuery.setQueryConfig(searchContext.getQueryConfig());
specialityQuery.add(contextQuery, BooleanClauseOccur.MUST);
BooleanQuery idFilter = BooleanQueryFactoryUtil.create(searchContext);
for (String speciality : specialities) {
TermQuery termQuery = TermQueryFactoryUtil.create(searchContext, "fruit", speciality);
idFilter.add(termQuery, BooleanClauseOccur.SHOULD);
LOGGER.info(" Term Query " + idFilter);
}
specialityQuery.add(idFilter, BooleanClauseOccur.MUST);
But this doesn’t work. Any other ideas?
P.S - Question posted on Liferay as well - https://www.liferay.com/community/forums/-/message_boards/message/48383912
Tina

SQL Compare Characters in two strings count total identical

So the over all on this is I have two different systems and in both systems I have customers, unfortunately both systems allow you to type in the business name freehand so you end up with the example below.
Column A has a value of "St John Baptist Church"
Column B has a value of "John Baptist St Church"
What I need to come up with is a query that can compare the two columns to find the most closely matched values.
From there I plan to write a web app where I can have someone go through and validate all of the entries. I would enter in some example of what I have done, but unfortunately I honestly dont even know if what I am asking for is even possible. I would think it is though in this day and age I am sure I am not the first one to try to attempt this.
You could try and create a script something like this php script to help you:
$words = array();
$duplicates = array();
function _compare($value, $key, $array) {
global $duplicates;
$diff = array_diff($array, $value);
if (!empty($diff)) {
$duplicates[$key] = array_keys($diff);
}
return $diff;
}
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$query = "SELECT id, business_name FROM table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_object()) {
$pattern = '#[^\w\s]+#i';
$row->business_name = preg_replace($pattern, '', $row->business_name);
$_words = explode(' ', $row->business_name);
$diff = array_walk($words, '_compare', $_words);
$words[$row->id][] = $_words;
$result->close();
}
}
$mysqli->close();
This is not tested but you need something like this, because I don't think this is possible with SQL alone.
---------- EDIT ----------
Or you could do a research on what the guys in the comment recommend Levenshtein distance in T-SQL
Hope it helps, good luck!

Group By Sum Linq to SQL in C#

Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don't understand enough to apply other solutions to my own.
I have a view in my database called view_ProjectTimeSummary, this has the following fields:
string_UserDescription
string_ProjectDescription
datetime_Date
double_Hours
I have a method which accepts a to and from date parameter and first creates this List<>:
List<view_UserTimeSummary> view_UserTimeSummaryToReturn =
(from linqtable_UserTimeSummaryView
in datacontext_UserTimeSummary.GetTable<view_UserTimeSummary>()
where linqtable_UserTimeSummaryView.datetime_Week <= datetime_To
&& linqtable_UserTimeSummaryView.datetime_Week >= datetime_From
select linqtable_UserTimeSummaryView).ToList<view_UserTimeSummary>();
Before returning the List (to be used as a datasource for a datagridview) I filter the string_UserDescription field using a parameter of the same name:
if (string_UserDescription != "")
{
view_UserTimeSummaryToReturn =
(from c in view_UserTimeSummaryToReturn
where c.string_UserDescription == string_UserDescription
select c).ToList<view_UserTimeSummary>();
}
return view_UserTimeSummaryToReturn;
How do I manipulate the resulting List<> to show the sum of the field double_Hours for that user and project between the to and from date parameters (and not separate entries for each date)?
e.g. a List<> with the following fields:
string_UserDescription
string_ProjectDescription
double_SumOfHoursBetweenToAndFromDate
Am I right that this would mean I would have to return a different type of List<> (since it has less fields than the view_UserTimeSummary)?
I have read that to get the sum it's something like 'group / by / into b' but don't understand how this syntax works from looking at other solutions... Can someone please help me?
Thanks
Steve
Start out by defining a class to hold the result:
public class GroupedRow
{
public string UserDescription {get;set;}
public string ProjectDescription {get;set;}
public double SumOfHoursBetweenToAndFromDate {get;set;}
}
Since you've already applied filtering, the only thing left to do is group.
List<GroupedRow> result =
(
from row in source
group row by new { row.UserDescription, row.ProjectDescription } into g
select new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
}
).ToList();
(or the other syntax)
List<GroupedRow> result = source
.GroupBy(row => new {row.UserDescription, row.ProjectDescription })
.Select(g => new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
})
.ToList();

Criteria API - Using UPPER in a ElementCollection

I have a class
#Entity
public class Person{
...
#ElementCollection
private Set<String> tags;
...
}
I want to use the JPA 2.0 Criteria API to search over these tags - but in a case insensitive way. Thus I want to both set the search parameter to UPPER and the column to UPPER (Pseudo-SQL: select p.* from Person p join Tags t on p.id=t.pId where upper(t.name)=upper('searchParameter'); )
Here is my code without the UPPER on the tags:
CriteriaBuilder builder = this.em.getCriteriaBuilder();
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
return this.em.createQuery(query.select(root).where(
builder.isMember(builder.upper(builder.literal(searchTag)),
root.get(Person_.tags)))).getResultList();
where searchTag is the input parameter.
How can I assign the UPPER to the Person_.tags "Column"?
In other words I want to write this Query with Criteria API:
SELECT p FROM Person p JOIN p.tags t WHERE UPPER(t) = UPPER('searchString')
Thank you
Ok, I finally have the solution:
cQuery.where(
builder.equal(
builder.upper(cQuery.from(Relation.class).join(Relation_.aliase)
.as(String.class)),
builder.upper(builder.literal(alias))
)
);
One has to use the ".as(..)" method.
suburbCriteria = criteriaBuilder.equal(
criteriaBuilder.upper(root.get(Property_.suburb)),
criteriaBuilder.upper(criteriaBuilder.literal(searchBean.getSuburb())));
You need to call upper and literal property name on joined Tags from Person.
CriteriaBuilder builder = this.em.getCriteriaBuilder();
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
Join<Person, Tag> tags = root.join(Person_.tags);
query.where(builder.isMember(
builder.upper(builder.literal(searchTag)),
builder.upper(builder.literal(tags.get(Tag_.name)))
));
return this.em.createQuery(query).getResultList();
I omitted query.select(root), not sure if it is required.
Tou can also omit builder.literal() on Tag_.name since is String.
If I am wrong somewhere, please edit my answer for further users.
Hope this helps.