Skip to content

Instantly share code, notes, and snippets.

@Getty
Created September 27, 2011 04:07
Show Gist options
  • Select an option

  • Save Getty/1244324 to your computer and use it in GitHub Desktop.

Select an option

Save Getty/1244324 to your computer and use it in GitHub Desktop.
most stupid website search
if ($c->req->params->{q}) {
my $q = $c->req->params->{q};
$c->stash->{q} = $q;
my @words = map { lc($_) } split(/ /,$q);
my $like = '%'.join('%',@words).'%';
my @results = $c->model('DB::Search')->search({
content => { like => '%'.$q.'%' },
})->all;
my %res;
for (@results) {
my $bestpos;
for my $w (@words) {
my $index = CORE::index($_->content,$w)+1;
if (!$bestpos) {
$bestpos = $index;
} else {
$bestpos = $index if $index < $bestpos;
}
}
if ($bestpos) {
while (defined $res{$bestpos}) {
$bestpos += 1;
};
$res{$bestpos} = $_;
}
}
my @sorted;
for (sort { $a <=> $b } keys %res) {
push @sorted, $res{$_};
}
$c->stash->{result} = [@sorted];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment