Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer exact matches in Link Search results sorting #67367

Merged
merged 2 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -270,12 +270,29 @@ export function sortResults( results: SearchResult[], search: string ) {
for ( const result of results ) {
if ( result.title ) {
const titleTokens = tokenize( result.title );
const matchingTokens = titleTokens.filter( ( titleToken ) =>
searchTokens.some( ( searchToken ) =>
titleToken.includes( searchToken )
const exactMatchingTokens = titleTokens.filter( ( titleToken ) =>
searchTokens.some(
( searchToken ) => titleToken === searchToken
)
);
scores[ result.id ] = matchingTokens.length / titleTokens.length;
const subMatchingTokens = titleTokens.filter( ( titleToken ) =>
searchTokens.some(
( searchToken ) =>
titleToken !== searchToken &&
titleToken.includes( searchToken )
)
);

// The score is a combination of exact matches and sub-matches.
// More weight is given to exact matches, as they are more relevant (e.g. "cat" vs "caterpillar").
// Diving by the total number of tokens in the title normalizes the score and skews
// the results towards shorter titles.
const exactMatchScore =
( exactMatchingTokens.length / titleTokens.length ) * 10;

const subMatchScore = subMatchingTokens.length / titleTokens.length;

scores[ result.id ] = exactMatchScore + subMatchScore;
} else {
scores[ result.id ] = 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,43 @@ describe( 'sortResults', () => {
6,
] );
} );

it( 'orders results to prefer direct matches over sub matches', () => {
const results = [
{
id: 1,
title: 'News',
url: 'http://wordpress.local/news/',
type: 'page',
kind: 'post-type',
},
{
id: 2,
title: 'Newspaper',
url: 'http://wordpress.local/newspaper/',
type: 'page',
kind: 'post-type',
},
{
id: 3,
title: 'News Flash News',
url: 'http://wordpress.local/news-flash-news/',
type: 'page',
kind: 'post-type',
},
{
id: 4,
title: 'News',
url: 'http://wordpress.local/news-2/',
type: 'page',
kind: 'post-type',
},
];
const order = sortResults( results, 'News' ).map(
( result ) => result.id
);
expect( order ).toEqual( [ 1, 4, 3, 2 ] );
} );
} );

describe( 'tokenize', () => {
Expand Down
Loading