7 Commits

Author SHA1 Message Date
52a0cde401 (front) Autocomplete search on dashboard with Datalist
Create Elasticsearch service to search suggestions

Send to page when choose a suggestion - bad way
It's impossible to use Object with datalist
So it's impossible to distinguish an album from an artist if they have
the same name
2021-08-22 17:04:29 +02:00
5fbcfbae68 (front) Update package-lock 2021-08-22 17:04:25 +02:00
74c6f99fa5 (back) Suggester: Change ELS search analyzer for specific char
Implementing search in dashboard revealed problems when search with specific char (francois perusse)
Note: it's also possible to specify an analyzer for ingestion

(cherry picked from commit 24da127750c995c55d54876a1be8a4ad3bf9ce9c)
2021-08-22 17:02:14 +02:00
60e1fb2e74 (back) Suggester: Improve processor - more generic
Process album & artist with a calculated fields
Separate main
Show progress

(cherry picked from commit fc8407cc6a51fe18b14169b3a3f0e4fc363beb4f)
2021-08-22 17:01:19 +02:00
520d0be595 (back) Suggester V3: Process album in a separate way
(cherry picked from commit ebbeeccfb8535dbb67240d2c68c7dc9a4da7e7f8)
2021-08-22 17:01:04 +02:00
8121f3d751 (back) Suggester V2: Process album data
(cherry picked from commit dd322405d047d49e51d528341cbd008d7a98b6ab)
2021-08-22 17:01:00 +02:00
436edaf3f2 (back) Suggester V1: Process artist data
(cherry picked from commit 02f5705fde37e1aaef5c68de62aafe45fc86d490)
2021-08-22 17:00:01 +02:00
8 changed files with 17017 additions and 31 deletions

16733
dashboard/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'; import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component'; import { DashboardComponent } from './dashboard/dashboard.component';
@@ -26,6 +27,7 @@ import { AlbumsComponent } from './albums/albums.component';
imports: [ imports: [
BrowserModule, BrowserModule,
HttpClientModule, HttpClientModule,
FormsModule,
AppRoutingModule AppRoutingModule
], ],
declarations: [ declarations: [

View File

@@ -77,6 +77,25 @@
</div> </div>
</div> </div>
<form class="navbar-form">
<div class="form-group" style="display:inline;">
<div class="input-group" style="display:table;">
<span class="input-group-addon" style="width:1%;">
<span class="glyphicon glyphicon-search"></span>
</span>
<input class="form-control" type="text" name="search" placeholder="Search Here" autocomplete="off" autofocus="autofocus"
id="searchSuggest"
list="dynmicUserIds"
[(ngModel)]="searchTerm"
(keyup)="onSearchChange()"
(change)="onSearchSelected($event)">
<datalist id="dynmicUserIds">
<option *ngFor="let item of suggested" [value]="item.name" [label]="item.type" [id]="item">{{item}}</option>
</datalist>
</div>
</div>
</form>
<div class="col-md-12"> <div class="col-md-12">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>

View File

@@ -1,10 +1,12 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ElsService } from './../els.service'; import { ElsService } from './../els.service';
import { Song } from './../model/song'; import { Song } from './../model/song';
import { Bucket } from './../model/bucket'; import { Bucket } from './../model/bucket';
import { Album } from './../model/album'; import { Album } from './../model/album';
import { Artist } from './../model/artist'; import { Artist } from './../model/artist';
import { Suggested } from '../model/suggested';
@Component({ @Component({
selector: 'app-dashboard', selector: 'app-dashboard',
@@ -30,7 +32,10 @@ export class DashboardComponent implements OnInit {
lastAddedAlbums: Bucket[] = []; lastAddedAlbums: Bucket[] = [];
albumArtists = []; albumArtists = [];
constructor(private elsService: ElsService) { } searchTerm = ''
suggested : Suggested[] = []
constructor(private elsService: ElsService, private route: Router) { }
ngOnInit(): void { ngOnInit(): void {
this.elsService.getTime().then(result => { this.elsService.getTime().then(result => {
@@ -113,4 +118,19 @@ export class DashboardComponent implements OnInit {
} }
}); });
} }
onSearchChange() {
this.elsService.getSuggest(this.searchTerm).subscribe(result => this.suggested = result);
}
onSearchSelected($event) {
let selected = $event.target.value
// FIXME Not possible to get good element (just value)
// Need to use a plugin to do this correctly
this.suggested.forEach(element => {
if (element.name == selected) {
this.route.navigate(['/' + element.type + '/' + element.name])
}
});
}
} }

View File

@@ -8,6 +8,7 @@ import { Song } from './model/song';
import { Album } from './model/album'; import { Album } from './model/album';
import { Artist } from './model/artist'; import { Artist } from './model/artist';
import { Bucket } from './model/bucket'; import { Bucket } from './model/bucket';
import { Suggested } from './model/suggested';
@Injectable() @Injectable()
export class ElsService { export class ElsService {
@@ -15,6 +16,7 @@ export class ElsService {
public static readonly SONG_INDEX_NAME = '/itunes-songs'; public static readonly SONG_INDEX_NAME = '/itunes-songs';
public static readonly ARTIST_INDEX_NAME = '/itunes-artists'; public static readonly ARTIST_INDEX_NAME = '/itunes-artists';
public static readonly ALBUM_INDEX_NAME = '/itunes-albums'; public static readonly ALBUM_INDEX_NAME = '/itunes-albums';
public static readonly SUGGEST_INDEX_NAME = '/itunes-suggest';
protected static readonly ACTION_SEARCH = '/_search'; protected static readonly ACTION_SEARCH = '/_search';
protected static readonly ACTION_COUNT = '/_count'; protected static readonly ACTION_COUNT = '/_count';
@@ -381,6 +383,34 @@ export class ElsService {
); );
} }
getSuggest(text: string): Observable<Suggested[]> {
console.log('search sugget: ' + text);
return this.http
.post<any>(this.elsUrl + ElsService.SUGGEST_INDEX_NAME + ElsService.ACTION_SEARCH,
JSON.stringify({
'_source': ['album', 'artist'],
'suggest': {
'album-suggest': {
'prefix': text,
'completion': {
'field': 'album_suggest'
}
},
'artist-suggest': {
'prefix': text,
'completion': {
'field': 'artist_suggest'
}
}
}
}), {headers: this.headers})
.pipe(
map(res => this.responseSuggesterToSuggested(res, 'album-suggest', 'artist-suggest')),
catchError(error => this.handleError(error, 'getSuggest(' + text + ')'))
);
}
/** Process a result to return just one result. /** Process a result to return just one result.
* Used to get an album or an artist. * Used to get an album or an artist.
* Take a name to put in console output if no result or more than one result. * Take a name to put in console output if no result or more than one result.
@@ -462,6 +492,20 @@ export class ElsService {
return result; return result;
} }
protected responseSuggesterToSuggested(res: any, ...suggestName: string[]): Suggested[] {
const result: Array<Suggested> = []
suggestName.forEach(sname => {
res['suggest'][sname][0]['options'].forEach(option => {
let suggest = new Suggested()
// TODO If more than one key, raise exception
suggest.type = String(Object.keys(option['_source']))
suggest.name = option['_source'][suggest.type]
result.push(suggest)
});
});
return result;
}
protected handleError(error: any, origin: string): Promise<any> { protected handleError(error: any, origin: string): Promise<any> {
console.error('An error occurred!'); console.error('An error occurred!');
console.error('Origin function: ', origin); console.error('Origin function: ', origin);

View File

@@ -0,0 +1,8 @@
export class Suggested {
name: string;
type: string;
public toString() : string {
return `${this.name} (${this.type})`;
}
}

137
suggester.es Normal file
View File

@@ -0,0 +1,137 @@
DELETE itunes-suggest
PUT /itunes-suggest
{
"settings": {
"analysis": {
"filter": {
"french_stop": {
"type": "stop",
"stopwords": "_french_"
},
"english_stop": {
"type": "stop",
"stopwords": "_english_"
}
},
"analyzer": {
"names": {
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding",
"french_stop",
"english_stop"
]
}
}
}
},
"mappings": {
"properties": {
"artist_suggest": {
"type": "completion",
"search_analyzer": "names"
},
"artist": {
"type": "keyword"
},
"album_suggest": {
"type": "completion",
"search_analyzer": "names"
},
"album": {
"type": "keyword"
}
}
}
}
// Also possible to specify analyze for ingesting => https://stackoverflow.com/questions/48304499/elasticsearch-completion-suggester-not-working-with-whitespace-analyzer
// Problem with word EP, SP
GET itunes-suggest/_analyze
{
"analyzer": "names",
"text": "the servent"
}
GET itunes-suggest/_search
POST itunes-suggest/_search
{
"_source" : "artist",
"suggest": {
"name-suggest": {
"prefix": "sou",
"completion": {
"field": "artist_suggest"
}
}
}
}
POST itunes-suggest/_search
{
"_source" : "album",
"suggest": {
"name-suggest": {
"prefix": "new",
"completion": {
"field": "album_suggest",
"size": 20
}
}
}
}
POST itunes-suggest/_search
{
"_source": ["album", "artist"],
"suggest": {
"alb-suggest": {
"prefix": "sou",
"completion": {
"field": "album_suggest"
}
},
"ar-suggest": {
"prefix": "sou",
"completion": {
"field": "artist_suggest"
}
}
}
}
POST itunes-suggest/_search
{
"_source": ["album", "artist"],
"suggest": {
"alb-suggest": {
"prefix": "Francois",
"completion": {
"field": "album_suggest"
}
},
"ar-suggest": {
"prefix": "Francois",
"completion": {
"field": "artist_suggest"
}
}
}
}
POST itunes-suggest/_search
{
"suggest": {
"ar-suggest": {
"prefix": "Femme",
"completion": {
"field": "artist_suggest"
}
}
}
}

83
suggester.py Normal file
View File

@@ -0,0 +1,83 @@
import requests
import json
import sys
ELS_URL ='http://localhost:9200'
INDEX = 'itunes-suggest'
class NoGoodDataException(Exception):
def __init__(self, message):
super().__init__(message)
def get_tokens(data: str) -> list:
if not data:
return []
query = {
"analyzer": "names",
"text" : data
}
url = '{}/{}/_analyze'.format(ELS_URL, INDEX)
r = requests.get(url, json=query)
if not 'tokens' in r.json():
print('ERROR: Not tokens in result')
print('Input: ' + str(data))
print('Request: ' + str(r.json()))
raise NoGoodDataException('Data is not correct to get tokens')
return [t['token'] for t in r.json()['tokens']]
def post_document(name: str, input: list, field_name: str) -> bool:
suggest_name = field_name + '_suggest'
element = {
field_name: name,
suggest_name: input
}
# Filter empty keys
# element = {k: v for k, v in element.items() if v}
url = '{}/{}/_doc'.format(ELS_URL, INDEX)
resp = requests.post(url, json=element)
if resp.status_code != 201:
print('ELS Response KO')
print(resp.status_code)
print(resp.text)
return
el_id = resp.json()['_id']
# print('Post_element - Element created: ' + el_id)
return el_id
def process_file(file_name: str, field_name: str) -> int:
print('Process file: ' + file_name)
with open(file_name, 'r') as o_file:
lines = o_file.readlines()
count = 0
i = 0
for line in lines:
i += 1
sys.stdout.write(str(int((i/len(lines))*100)) + '%')
sys.stdout.flush()
sys.stdout.write("\b" * (40+1)) # return to start of line, after '['
data = json.loads(line)
if "Artist" in data:
try :
input = get_tokens(data[field_name])
post_document(name=data[field_name], input=input, field_name=field_name.lower())
count += 1
except NoGoodDataException:
print('ERROR WITH DATA')
print(str(data))
print('File processed\n')
return count
if __name__ == '__main__':
# Using readlines()
count = 0
count += process_file('/home/budd/workspace/iTunes/es-albums.json', 'Album')
count += process_file('/home/budd/workspace/iTunes/es-artists.json', 'Artist')
print('Created documents: ' + str(count))